Memcached is a high-performance, distributed in-memory caching system that reduces database load by storing frequently accessed data in RAM. Common use cases include caching query results from databases like MariaDB, storing PHP or Python session data, accelerating API responses, and serving as a shared cache layer across multiple application servers. If your web application repeatedly queries the same data from a database or external API, Memcached can return cached results in microseconds instead of milliseconds.
This guide covers two installation methods: the APT package from Ubuntu’s repositories (recommended for most deployments) and source compilation for users who need the latest upstream release or custom build flags. Both paths include service management, configuration, firewall rules, and language library integration for PHP, Python, and Perl.
These steps apply to Ubuntu 26.04, 24.04, and 22.04. Commands are identical across releases unless noted otherwise.
Default Memcached Versions by Ubuntu Release
Ubuntu’s repositories include different Memcached versions depending on your release. The APT package receives security updates automatically but tracks the version available when your Ubuntu release was published:
| Ubuntu Release | Memcached Version | Support Status |
|---|---|---|
| Ubuntu 26.04 | 1.6.40 | Latest LTS (current) |
| Ubuntu 24.04 | 1.6.24 | LTS until April 2029 |
| Ubuntu 22.04 | 1.6.14 | LTS until April 2027 |
For most deployments, the repository version provides stability and automatic security patches. Compile from source only if you specifically need features from a newer release or require custom build options like SASL authentication support.
Choose Your Memcached Installation Method
Ubuntu’s repositories provide a stable, automatically updated Memcached package suitable for most production deployments. Source compilation gives you access to the latest upstream release and custom build options but requires manual updates.
| Method | Channel | Version | Updates | Best For |
|---|---|---|---|---|
| APT (Ubuntu Repositories) | Ubuntu Repos | Distribution default | Automatic via apt upgrade | Production servers, most deployments |
| Compile from Source | Upstream | Latest stable (1.6.40) | Manual recompilation | Custom build flags, newest features |
For most users, the APT method is recommended because it provides automatic security updates and integrates with Ubuntu’s service management. Only compile from source if you specifically need features unavailable in your Ubuntu release or require custom build options like SASL authentication.
Method 1: Install Memcached via APT
Update Package Index
Update your package lists and process any pending upgrades before installing Memcached:
sudo apt update && sudo apt upgrade
Install Memcached from Ubuntu Repositories
Install the Memcached server and optional management tools:
sudo apt install memcached libmemcached-tools
The libmemcached-tools package provides utilities like memstat for monitoring cache statistics and memflush for clearing all cached data. These tools are optional but useful for troubleshooting and maintenance.
Verify Memcached Installation
Confirm the installation by checking the version:
memcached -V
Expected output (version varies by Ubuntu release):
memcached 1.6.40
The APT package also enables Memcached as a systemd service, so it starts automatically at boot and is already running after installation.
Method 2: Install Memcached from Source
Compile from source when you need the latest upstream release (currently 1.6.40) or custom build options like SASL authentication. This method requires manual recompilation for updates but gives you full control over the build configuration.
Fetch the Memcached Source
Download the latest stable release from the official site. The https://memcached.org/latest URL redirects to the current release tarball:
cd ~
wget https://memcached.org/latest -O memcached-latest.tar.gz
Using -O memcached-latest.tar.gz gives the downloaded file a predictable name. If you want to explore more download options, the wget command examples guide covers additional patterns.
Unpack the Memcached Source Archive
Extract the compressed archive:
tar -xvzf memcached-latest.tar.gz
This creates a directory named memcached-1.6.40 (or the current version number) containing the source files.
Install Build Dependencies
Install the compiler, build tools, and required development libraries:
sudo apt install build-essential libevent-dev libc6-dev
The libevent-dev package provides the event notification library that Memcached uses for handling network connections efficiently.
For SASL authentication support (optional), also install the SASL development headers:
sudo apt install libsasl2-dev
Configure the Build
Navigate to the extracted source directory:
cd memcached-1.6.40
Run the configure script to prepare the build. The --prefix=/usr/local installs binaries to /usr/local/bin where they take precedence over APT-installed versions:
./configure --prefix=/usr/local
If you installed libsasl2-dev and want SASL authentication, add the flag:
./configure --prefix=/usr/local --enable-sasl
The configure script checks for required libraries and generates the Makefile. Look for lines confirming libevent detection:
checking for libevent directory... (system) checking for library containing event_base_new... -levent configure: creating ./config.status config.status: creating Makefile
Compile the Memcached Source Code
Compile the source using all available CPU cores to speed up the build:
make -j$(nproc)
The -j$(nproc) flag runs multiple compilation jobs in parallel. On a typical server, compilation completes in under a minute.
After compilation, verify the binary was built correctly from the build directory:
./memcached -V
memcached 1.6.40
Install the Compiled Binaries
Install the compiled binary system-wide:
sudo make install
Verify Installation (Source Method)
Confirm the installed version is accessible from your PATH:
memcached -V
memcached 1.6.40
You can also verify the binary location to confirm the source-compiled version takes precedence:
which memcached
/usr/local/bin/memcached
Set Up a systemd Service (Source Install)
Source-compiled Memcached requires a systemd unit file to manage it as a service. The APT package includes a pre-configured unit with security hardening; follow these steps to create a similar setup for your source build.
Create a Dedicated User and Group
Create a system account without login access to run the Memcached daemon:
sudo useradd -r -s /usr/sbin/nologin -U -M memcache
The flags create a system user (-r) with no login shell (-s /usr/sbin/nologin), a matching group (-U), and no home directory (-M).
Create the Service File
Create the systemd unit file:
sudo nano /etc/systemd/system/memcached.service
Add the following configuration. This includes security hardening directives similar to the APT package’s unit file. Adjust the ExecStart flags (-m for memory, -c for max connections, -t for threads) to match your server resources:
[Unit]
Description=Memcached In-Memory Object Cache
After=network.target
Documentation=man:memcached(1)
[Service]
Type=simple
User=memcache
Group=memcache
ExecStart=/usr/local/bin/memcached -u memcache -m 64 -p 11211 -l 127.0.0.1 -c 1024 -t 4
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
LimitNOFILE=65535
# Security hardening
PrivateTmp=true
ProtectSystem=full
NoNewPrivileges=true
PrivateDevices=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictRealtime=true
[Install]
WantedBy=multi-user.target
The security directives isolate Memcached from the rest of the system: PrivateTmp gives it a private /tmp directory, ProtectSystem mounts system directories read-only, and NoNewPrivileges prevents privilege escalation.
Save and Close the Editor
In nano, press Ctrl+X, then Y, then Enter to save and exit.
Reload systemd and Enable the Service
Reload the systemd configuration to recognize the new unit, then enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable memcached --now
The --now flag combines enabling (auto-start at boot) with immediate startup in one command.
Memcached Service Commands
Ubuntu uses systemd to manage Memcached. These commands work for both APT and source installations (after creating the systemd unit).
Check Service Status
The APT package enables Memcached automatically after installation. Verify the service is running:
systemctl status memcached
A healthy service shows active (running):
● memcached.service - memcached daemon
Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; preset: enabled)
Active: active (running) since Thu 2026-01-30 10:15:42 UTC; 5min ago
Docs: man:memcached(1)
Main PID: 1234 (memcached)
Tasks: 10 (limit: 4567)
Memory: 12.3M
CPU: 150ms
CGroup: /system.slice/memcached.service
If the service is not running, start and enable it:
sudo systemctl enable memcached --now
Common Service Commands
Start Memcached manually:
sudo systemctl start memcached
Enable auto-start at boot:
sudo systemctl enable memcached
Stop Memcached:
sudo systemctl stop memcached
Disable auto-start at boot:
sudo systemctl disable memcached
Restart Memcached (required after configuration changes):
sudo systemctl restart memcached
Confirm the Listening Port
Verify Memcached is listening on the loopback interface:
sudo ss -tlnp | grep memcached
The -p flag requires root privileges to display process names. Expected output shows listeners on both IPv4 and IPv6 loopback addresses:
LISTEN 0 1024 127.0.0.1:11211 0.0.0.0:* users:(("memcached",pid=1234,fd=26))
LISTEN 0 1024 [::1]:11211 [::]:* users:(("memcached",pid=1234,fd=27))
This confirms Memcached is bound to localhost only (127.0.0.1 and ::1) and not accessible from the network, which is the secure default configuration.
Configure Memcached
Configuration differs based on your installation method. APT installs use a Debian-style config file parsed by the systemd service wrapper. Source installs pass flags directly in the systemd unit’s ExecStart line.
Memcached has no built-in authentication by default. Exposing it to the internet without additional protection (firewall, SASL) invites abuse. Keep it bound to
127.0.0.1and::1unless you specifically need remote access from trusted networks.
APT Install: Edit /etc/memcached.conf
Open the configuration file:
sudo nano /etc/memcached.conf
The default configuration uses Debian-style flag format. Key settings in a typical production configuration:
# Memory in MB (default: 64)
-m 64
# TCP port (default: 11211)
-p 11211
# Run as this user
-u memcache
# Bind addresses (loopback for security)
-l 127.0.0.1
-l ::1
# Maximum simultaneous connections (default: 1024)
# -c 1024
# Disable UDP (reduces attack surface)
# -U 0
# Log file location
logfile /var/log/memcached.log
The -l flag appears twice to bind both IPv4 (127.0.0.1) and IPv6 (::1) loopback addresses. This is Ubuntu’s secure default.
Listening Address
Memcached binds to 127.0.0.1 and ::1 by default. Only change the -l parameter if you need remote access, and always protect it with a firewall or private network.
Disable UDP
UDP support is disabled by default in recent Memcached versions because it was exploited in amplification attacks. If you’re using an older version, explicitly disable it:
-U 0
Adjust Memory Allocation
The -m flag sets the maximum memory Memcached uses for storing cached items. The default is 64 MB, which is conservative. For a dedicated caching server, increase this based on available RAM:
# Allocate 2 GB for caching
-m 2048
Leave at least 1-2 GB free for the operating system and other processes. Memcached grows to this limit gradually as items are cached; it does not allocate all memory immediately at startup.
Apply Configuration Changes
After editing the configuration, restart Memcached to apply the updates:
sudo systemctl restart memcached
Additional Configuration Options
Beyond basic settings, Memcached offers tuning options for performance and security. Add these flags to /etc/memcached.conf for APT installs or the ExecStart line in your systemd unit for source builds, then restart the service.
For comprehensive documentation on all available options, see the official Memcached documentation.
Specify User
Run Memcached as a dedicated non-root user. The APT package already configures this:
-u memcache
Enable Large Memory Pages
Huge pages can improve performance on systems with large cache allocations by reducing TLB misses. Enable with -L (requires kernel huge pages configured):
-L
Configure Maximum Item Size
The default maximum item size is 1 MB. Increase this if you need to cache larger objects:
# Allow items up to 5 MB
-I 5m
Be aware that very large items can cause memory fragmentation.
Set Thread Count
Memcached defaults to 4 threads. Match this to your available CPU cores for high-throughput workloads:
# Use 8 threads
-t 8
Adjust Idle Timeout
Set idle connection timeout (in seconds) to close abandoned client connections:
-o idle_timeout=600
Enable SASL Authentication
SASL provides username/password authentication. Enable with -S (requires building with --enable-sasl or using the APT package with SASL libraries installed):
-S
After any configuration changes, restart Memcached:
sudo systemctl restart memcached
Secure Memcached with UFW
Memcached binds to localhost by default and requires no firewall rules for local use. If you expose it to a network for clustering or remote clients, restrict access with UFW (Uncomplicated Firewall). For a broader overview, see the guide to installing and configuring UFW firewall on Ubuntu.
Check UFW Status
Check if UFW is installed and active:
sudo ufw status
If UFW is not installed:
sudo apt install ufw
Allow SSH Before Enabling UFW
Before enabling UFW, allow SSH to avoid locking yourself out of a remote server:
sudo ufw allow OpenSSH
Enabling UFW without an SSH rule immediately disconnects remote sessions. Always add your management access rule first.
Create UFW Rules for Memcached
Allow only trusted sources to connect to Memcached.
Allow a Single IP
Replace 192.168.1.100 with the trusted client’s IP address:
sudo ufw allow proto tcp from 192.168.1.100 to any port 11211
Allow a Subnet (Cluster)
For internal clusters, allow an entire subnet. Replace 10.0.0.0/24 with your network range:
sudo ufw allow proto tcp from 10.0.0.0/24 to any port 11211
Enable UFW
With your rules configured, enable the firewall:
sudo ufw enable
If UFW was already active, reload it to apply new rules:
sudo ufw reload
Verify UFW Rules
List active rules to confirm your configuration:
sudo ufw status numbered
Example output with SSH and Memcached rules:
Status: active
To Action From
-- ------ ----
[ 1] OpenSSH ALLOW IN Anywhere
[ 2] 11211/tcp ALLOW IN 10.0.0.0/24
The numbered flag shows rule numbers, which you need if you want to delete a specific rule later (e.g., sudo ufw delete 2). For more firewall management options, see the Ubuntu firewall management guide.
Install Memcached Language Libraries
Applications connect to Memcached through client libraries. The sections below install packages for PHP, Python, and Perl.
PHP Memcached Extension
PHP applications (including WordPress, Laravel, and Drupal) use the php-memcached extension. Install it alongside PHP if not already present.
Apache HTTP Server
Install PHP with Apache’s PHP module and the Memcached extension:
sudo apt install php php-cli libapache2-mod-php php-memcached
For additional PHP modules and version options, see the PHP on Ubuntu installation guide.
Enable the Extension and Restart Apache
Enable the extension and restart Apache to load it:
sudo phpenmod memcached && sudo systemctl restart apache2
For WordPress sites, plugins like W3 Total Cache can use Memcached for object caching. After installation, configure the plugin’s Object Cache settings to use Memcached with server 127.0.0.1:11211.
Nginx with PHP-FPM
For Nginx, install PHP-FPM instead of the Apache module:
sudo apt install php php-cli php-fpm php-memcached
Configure your Nginx server block to pass PHP requests to PHP-FPM. Adjust the socket path to match your installed PHP version (e.g., /run/php/php8.3-fpm.sock):
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Python
Install a Python Memcached client library:
sudo apt install python3-pymemcache
The pymemcache library is a modern, pure-Python client maintained by Pinterest.
Perl
Install the Perl Memcached client:
sudo apt install libcache-memcached-libmemcached-perl
Access Memcached from the Command Line
You can interact with Memcached directly for testing and diagnostics using Telnet or netcat. This is useful for verifying connectivity, checking cache statistics, and debugging.
Connect with Telnet
Connect to the local Memcached instance:
telnet localhost 11211
On success:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'.
If Telnet is not installed:
sudo apt install telnet
For more Telnet options, see the Telnet installation guide for Ubuntu.
Connect with Netcat
Netcat (nc) works without an interactive prompt, making it useful for scripts. Install the OpenBSD flavor if needed:
sudo apt install netcat-openbsd
Send a stats command and exit:
printf 'stats\r\nquit\r\n' | nc localhost 11211
Retrieve Statistics
Once connected via Telnet, run stats for a cache summary:
stats
This displays uptime, cache hit/miss counts, current items stored, memory usage, and active connections.
Inspect Memory Slabs
Memcached organizes memory into slabs. View slab allocation:
stats slabs
View item counts per slab:
stats items
List and Retrieve Cached Keys
List keys in a specific slab using stats cachedump. The syntax is stats cachedump [slab_id] [limit] where 0 returns all items:
stats cachedump 1 0
Example output:
ITEM testkey [9 b; 1296857316 s] END
Retrieve a key’s value with get:
get testkey
Example output:
VALUE testkey 0 9 test data END
Delete a Cached Key
Remove a specific key:
delete testkey
Response:
DELETED
To close the Telnet connection, type quit or press Ctrl+] then type quit.
Troubleshooting
Service Fails to Start
If Memcached fails to start after installation or configuration changes, check the systemd journal for error details:
journalctl -u memcached -e
A common error when using source builds looks like:
memcached.service: Failed at step USER spawning /usr/local/bin/memcached: No such process
This means the memcache user does not exist. Create it before starting the service:
sudo useradd -r -s /usr/sbin/nologin -U -M memcache
Another common cause is including -d (daemonize) in the ExecStart line. The systemd Type=simple expects the process to stay in the foreground; remove -d from your configuration.
Port Already in Use
If Memcached cannot bind to port 11211, another process is using it. Find the conflicting process:
sudo ss -tlnp | grep :11211
Example output showing another Memcached instance:
LISTEN 0 1024 127.0.0.1:11211 0.0.0.0:* users:(("memcached",pid=2345,fd=26))
Stop the conflicting process or change Memcached’s port in the configuration (-p 11212). If you have both APT and source installs, ensure only one systemd unit is enabled.
Connection Refused from Application
When your application reports connection errors but Memcached appears to be running, verify the service is listening:
systemctl is-active memcached && sudo ss -tlnp | grep memcached
If active but not listening, the process started but failed to bind. Check journal logs for binding errors. If listening but the application cannot connect, verify your application is configured to use 127.0.0.1:11211 (not localhost, which may resolve to IPv6 on some systems).
Test connectivity directly:
printf 'stats\r\nquit\r\n' | nc localhost 11211 | head -5
A working response returns statistics. No response or “Connection refused” indicates a configuration mismatch.
SASL Authentication Not Working
SASL authentication requires explicit compilation support. Check if your Memcached binary includes SASL:
memcached -h 2>&1 | grep -i sasl
If no output appears, SASL is not compiled in. For source builds, reinstall the SASL libraries and recompile:
sudo apt install libsasl2-dev sasl2-bin
cd ~/memcached-1.6.40
./configure --prefix=/usr/local --enable-sasl
make clean && make -j$(nproc)
sudo make install
The APT package supports SASL if the libraries are installed; add -S to the configuration to enable it.
Update Source-Compiled Memcached
If you compiled Memcached from source, use this script to check for updates and recompile when a new version is available. The script detects your installed version, fetches the latest release from memcached.org, and rebuilds only when an update exists.
Create the Update Script
Create a directory for the script and build files:
mkdir -p ~/memcached-build
Create the update script:
cat << 'EOF' | sudo tee /usr/local/bin/memcached-update.sh > /dev/null
#!/bin/bash
set -e
# Configuration
INSTALL_PREFIX="/usr/local"
BUILD_DIR="$HOME/memcached-build"
# Refuse to run as root
if [ "$(id -u)" -eq 0 ]; then
echo "Run this script as a regular user, not root."
exit 1
fi
# Check for required tools
for cmd in curl tar gcc make; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "Error: $cmd is required but not installed."
echo "Run: sudo apt install build-essential curl"
exit 1
fi
done
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"
# Get current installed version
CURRENT_VERSION=$($INSTALL_PREFIX/bin/memcached -V 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "none")
# Fetch latest version from memcached.org/latest redirect
echo "Checking for latest version..."
LATEST_URL=$(curl -sIL https://memcached.org/latest 2>&1 | grep -i '^location:' | tail -1 | tr -d '\r' | awk '{print $2}')
LATEST_VERSION=$(echo "$LATEST_URL" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
if [ -z "$LATEST_VERSION" ]; then
echo "Error: Could not detect latest version from memcached.org"
exit 1
fi
echo "Current version: $CURRENT_VERSION"
echo "Latest version: $LATEST_VERSION"
if [ "$CURRENT_VERSION" = "$LATEST_VERSION" ]; then
echo "Already up to date."
exit 0
fi
echo "Updating from $CURRENT_VERSION to $LATEST_VERSION..."
# Clean previous builds
rm -rf memcached-*/
# Download and extract
echo "Downloading memcached-$LATEST_VERSION..."
curl -fLO --progress-bar "https://memcached.org/files/memcached-$LATEST_VERSION.tar.gz"
tar -xzf "memcached-$LATEST_VERSION.tar.gz"
rm "memcached-$LATEST_VERSION.tar.gz"
cd "memcached-$LATEST_VERSION"
# Build
echo "Configuring..."
./configure --prefix="$INSTALL_PREFIX" > /dev/null
echo "Compiling..."
make -j"$(nproc)" > /dev/null
# Install
echo "Installing (requires sudo)..."
sudo make install > /dev/null
# Restart service if running
if systemctl is-active --quiet memcached 2>/dev/null; then
echo "Restarting memcached service..."
sudo systemctl restart memcached
fi
# Verify
NEW_VERSION=$($INSTALL_PREFIX/bin/memcached -V | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
echo "Successfully updated to memcached $NEW_VERSION"
EOF
sudo chmod +x /usr/local/bin/memcached-update.sh
Run the Update Script
Since the script is installed to /usr/local/bin, you can run it from any directory:
memcached-update.sh
Example output when already up to date:
Checking for latest version... Current version: 1.6.40 Latest version: 1.6.40 Already up to date.
When an update is available, the script downloads the new version, compiles it, installs the binary, and restarts the service if it was running.
Avoid automating this with cron. Compilation can fail due to missing dependencies or network issues. Run the script manually so you can monitor the output and address any problems.
Uninstall Memcached
Remove APT Installation
Stop the service and remove the packages along with their configuration files:
sudo systemctl disable memcached --now
sudo apt purge memcached libmemcached-tools
sudo apt autoremove
The purge command removes configuration files under /etc that the package owns. The autoremove command cleans up dependencies that are no longer needed.
Remove Source Installation
For source-compiled installations, stop and remove the systemd service, then delete the binary and build directory:
sudo systemctl disable memcached --now
sudo rm -f /etc/systemd/system/memcached.service
sudo systemctl daemon-reload
sudo rm -f /usr/local/bin/memcached /usr/local/bin/memcached-update.sh
Optionally remove the dedicated user and build files:
sudo userdel memcache
rm -rf ~/memcached-build ~/memcached-1.6.40 ~/memcached-latest.tar.gz
The cache data stored in Memcached exists only in RAM. When you stop the service, all cached data is immediately lost without needing any additional cleanup.
Frequently Asked Questions
Memcached is a simple key-value cache optimized for speed and memory efficiency. Redis offers richer data structures (lists, sets, sorted sets, hashes), persistence options, and pub/sub messaging. Use Memcached for straightforward caching where simplicity and raw speed matter most. Use Redis when you need data persistence, complex data types, or features like Lua scripting.
Start with the default 64 MB and monitor cache hit rates using the stats command. If you see high eviction counts (evictions in stats output), increase memory with the -m flag. A dedicated caching server might use 50-75% of available RAM, but always leave at least 1-2 GB for the operating system and other processes.
Memcached stores all data in RAM only. When you stop the service or reboot the server, all cached data is lost immediately. This is by design for performance. If you need persistent caching, use Redis with its AOF or RDB persistence options instead.
Yes, they use different default ports (Memcached: 11211, Redis: 6379) and can coexist without conflict. Some applications use Memcached for session storage and Redis for more complex caching needs. Ensure you have enough RAM for both services plus your application workload.
Conclusion
Memcached is now installed and configured on your Ubuntu system. You have a working cache service accessible from your applications via port 11211, with secure defaults that bind to localhost only. From here, configure your application’s caching layer to connect to Memcached, monitor cache hit rates using the stats command, and consider increasing memory allocation as your cache usage grows.
For persistent caching needs or more advanced data structures (lists, sets, pub/sub), consider Redis on Ubuntu as a complementary or alternative solution. Both can coexist when your application benefits from Memcached’s simplicity for basic key-value caching and Redis’s richer feature set for other use cases.
Formatting tips for your comment
You can use basic HTML to format your comment. Useful tags currently allowed:
<code>command</code>command<strong>bold</strong><em>italic</em><a href="URL">link</a><blockquote>quote</blockquote>