Memcached reduces database load by caching frequently accessed data in memory, making it essential for high-traffic web applications, session storage, and API response caching. Whether you’re running a WordPress site with object caching, a PHP application needing session persistence, or a distributed system requiring shared cache across multiple servers, Memcached provides the speed and simplicity to handle it. For workloads requiring data persistence or more complex data structures, consider installing Redis on Debian instead. By the end of this guide, you will have a working Memcached installation with service management, firewall configuration, and optional language library integrations for PHP, Python, and Perl.
Choose Your Memcached Installation Method
Debian offers Memcached through its default repositories, while compiling from source provides access to the latest version with potential performance improvements and bug fixes.
| Method | Channel | Version | Updates | Best For |
|---|---|---|---|---|
| APT Package Manager | Debian Repos | Distribution default | Automatic via apt upgrade | Most users who prefer stability and easy maintenance |
| Source Compilation | memcached.org | Latest stable | Manual recompilation | Users needing latest features or custom build options |
For most users, the APT method is recommended because it provides automatic security updates and seamless integration with Debian’s package management. Only compile from source if you specifically need features unavailable in the repository version or require custom compilation flags.
Memcached versions vary across Debian releases: Debian 11 includes Memcached 1.6.9, Debian 12 includes Memcached 1.6.18, and Debian 13 includes Memcached 1.6.38. Compiling from source provides the latest version (currently 1.6.39) on all supported Debian releases.
Method 1: Install Memcached via APT
For most users, the APT package manager provides the simplest installation path with automatic dependency resolution and security updates.
Update System Packages
Before installing any new software, ensure your system has the latest package versions and security updates:
sudo apt update && sudo apt upgrade
This command will update your package list and upgrade outdated packages to their latest versions.
Install Memcached Package
Next, install Memcached along with the management tools package:
sudo apt install memcached libmemcached-tools
Additionally, the libmemcached-tools package provides command-line utilities for interacting with and managing Memcached servers.
Verify Memcached Installation
After installation completes, confirm the installation by checking the installed version:
memcached -V
memcached 1.6.x
The version number depends on your Debian release. Additionally, check that the service is running:
systemctl status memcached
● memcached.service - memcached daemon
Loaded: loaded (/lib/systemd/system/memcached.service; enabled; preset: enabled)
Active: active (running)
Method 2: Install Memcached via Source Compilation
This section covers installing Memcached on your Debian system by compiling it from the source code. Installing from the source can be beneficial if you want to use the latest version of Memcached or customize the build for specific requirements.
Install Build Dependencies
First, install the necessary packages required to compile Memcached from source:
sudo apt install build-essential libevent-dev wget
The build-essential meta-package includes the GCC compiler and make utility, libevent-dev provides the asynchronous event library that Memcached requires, and wget downloads the source archive.
Download Memcached Source
Next, download the latest Memcached source code from the official release page:
wget https://memcached.org/latest -O memcached-latest.tar.gz
Extract Source Archive
Extract the downloaded source code:
tar -xzf memcached-latest.tar.gz
Then navigate to the extracted directory:
cd memcached-*/
The wildcard pattern automatically matches the extracted directory regardless of version number.
Configure Build Options
Use the --prefix= parameter to set the directory where Memcached binary and libraries will be installed:
./configure --prefix=/usr/local
The configure script checks for dependencies and prepares the build. Successfully completed output ends with:
config.status: creating Makefile config.status: executing depfiles commands
Compile Memcached Source Code
Compile the Memcached source code with the make command:
make
Test Memcached by confirming the current version:
./memcached --version
Install the Compiled Binary
Once the compilation process is complete, install Memcached by running the following command:
sudo make install
This command installs Memcached on your system, making it accessible from the command line. To ensure the system recognizes the new libraries, run the following:
sudo ldconfig
Verify the Installation of Memcached
To verify that Memcached is successfully installed, run the following command:
memcached -V
This command displays the installed version, confirming a successful source compilation:
memcached 1.6.39
Create Systemd Service for Memcached
Since source-compiled Memcached does not include a systemd service, you need to create one manually. First, create a dedicated user to run the service securely:
Important: If you previously installed Memcached via APT (Method 1), remove it first with
sudo apt remove --purge memcachedbefore creating this custom service. Both methods use the same service name and cannot coexist.
sudo useradd -r -s /sbin/nologin -U -M memcache
Next, create the systemd service file:
sudo nano /etc/systemd/system/memcached.service
Add the following content:
[Unit]
Description=Memcached Service (Source Compiled)
After=network.target
[Service]
Type=simple
User=memcache
Group=memcache
EnvironmentFile=-/etc/memcached-local.conf
ExecStart=/usr/local/bin/memcached -m ${MEMCACHED_MEMORY:-64} -p ${MEMCACHED_PORT:-11211} -u memcache -l ${MEMCACHED_LISTEN:-127.0.0.1} -U 0 $MEMCACHED_OPTIONS
Restart=always
[Install]
WantedBy=multi-user.target
Create the environment configuration file for easy customization:
sudo nano /etc/memcached-local.conf
Add the following default settings (adjust as needed):
MEMCACHED_MEMORY=64
MEMCACHED_PORT=11211
MEMCACHED_LISTEN=127.0.0.1
MEMCACHED_OPTIONS=""
Save the file, then reload systemd and start the service:
sudo systemctl daemon-reload
sudo systemctl enable memcached --now
Verify the service is running:
systemctl status memcached
● memcached.service - Memcached Service
Loaded: loaded (/etc/systemd/system/memcached.service; enabled; preset: enabled)
Active: active (running)
Managing Memcached Service Status
The following systemctl commands work identically for both APT and source-compiled installations. Memcached starts automatically after installation, but these commands help you control the service as needed.
Check the Memcached Service Status
By default, Memcached should be running after installation. To verify its status, use the systemctl command as follows:
systemctl status memcached
This command will display the current status of the Memcached service.
Start the Memcached Service
Alternatively, if Memcached is not running, you can start the service with the following command:
sudo systemctl start memcached
Enable Memcached on the System Boot
To ensure that the Memcached service starts automatically when your system boots, use the following command:
sudo systemctl enable memcached
Stop the Memcached Service
Conversely, if you need to stop the Memcached service, use this command:
sudo systemctl stop memcached
Disable Memcached on the System Boot
Similarly, to prevent the Memcached service from starting automatically at system boot, run the following command:
sudo systemctl disable memcached
Restart the Memcached Service
If you need to restart the Memcached service, for example, after making configuration changes, use this command:
sudo systemctl restart memcached
Important: Restarting Memcached clears all cached data since it stores everything in RAM. Schedule restarts during low-traffic periods or ensure your application can repopulate the cache quickly.
Verify Memcached is Listening on the Default Port
To verify that Memcached is listening on port 11211, use the ss command:
ss -tlnp | grep 11211
LISTEN 0 1024 127.0.0.1:11211 0.0.0.0:* users:(("memcached",pid=1234,fd=26))
The output confirms Memcached is listening on localhost (127.0.0.1) port 11211. If you need to check the running process details, use ps -ef | grep memcached.
Configure Memcached
Once installed, you can customize Memcached by editing the memcached.conf file. This section covers adjusting the listening IP address, disabling UDP, and changing the default memory allocation.
Open the Memcached Configuration File
The APT-installed Memcached uses /etc/memcached.conf for its configuration. Open it using nano:
sudo nano /etc/memcached.conf
Note: If you compiled Memcached from source (Method 2), your configuration is handled differently. The source-compiled systemd service uses environment variables from
/etc/memcached-local.confas created during installation. The configuration options below still apply, but you would modify them in that file using theMEMCACHED_OPTIONSvariable.
The default APT-installed configuration file contains settings like the following:
# Memcached configuration file
# This config is used by the APT-installed systemd service
# Memory allocation in megabytes
-m 64
# Listen port
-p 11211
# Run as this user
-u memcache
# Listen on localhost only (security best practice)
-l 127.0.0.1
# Disable UDP (prevents amplification attacks)
-U 0
# Maximum simultaneous connections
-c 1024
# Log file location
logfile /var/log/memcached.log
# PID file location
-P /var/run/memcached/memcached.pid
Adjust the Listening IP Address
By default, Memcached listens to IP address 127.0.0.1. Check the -l parameter in the configuration file and ensure it is set to the correct IP address. If you need to modify the IP address, replace 127.0.0.1 with the new IP address:
-l 127.0.0.1
Disable UDP (Optional)
Memcached UDP is rarely needed and has been exploited in amplification attacks (known as “memcrashed”). Unless your application specifically requires UDP, disable it by adding this line to the configuration file:
-U 0
Configure the Memory Allocation
The default memory allocation for Memcached is 64MB, which may not be sufficient for larger websites. Consider adjusting the memory allocation to a higher value to maximize Memcached.
To set the memory allocation, find the -m parameter in the configuration file and replace the default value with the desired amount (in MB). For example, to allocate 2GB of memory, set the value to 2048:
-m 2048
Adjust this setting based on your server’s available memory and requirements.
Performance Tuning Tips
For high-traffic deployments, consider these tuning recommendations based on workload patterns:
- Memory sizing: Allocate 25-50% of available RAM for Memcached on dedicated cache servers. On shared servers, start with 256-512MB and increase based on hit rates.
- Connection limits: The default 1024 connections suits most sites. High-traffic applications with many concurrent PHP workers may need 2048-4096. Monitor with
statscommand and checkcurr_connections. - Thread count: Match threads to CPU cores for CPU-bound workloads. For I/O-bound caching, 4 threads often suffices regardless of core count.
- Item size: Default maximum item size is 1MB. For larger cached objects, increase with
-I 2m(2MB) in the configuration file.
Save and Restart Memcached
After making the necessary changes, save and close the file by pressing CTRL+O and Enter to save, then CTRL+X to exit nano. Finally, restart the Memcached service for the changes to take effect:
sudo systemctl restart memcached
Advanced Configuration Options
Beyond the essential settings covered above, Memcached offers several advanced options for fine-tuning performance and security:
Specify the user and group
Memcached runs under a specific user and group specified using the -u parameter. For example, to run Memcached as the memcache user, add the following line to the configuration file:
-u memcache
Enable large memory pages
Enabling this feature may improve performance if your system supports large memory pages. To enable large memory pages, find the -L parameter and uncomment it (remove the # at the beginning of the line):
-L
Configure the maximum item size
Memcached has a default maximum item size of 1 MB. To increase the maximum item size, use the -I parameter followed by the desired size. For example, to set the maximum item size to 5MB, add the following line to the configuration file:
-I 5m
Set the maximum number of threads
Memcached uses four threads by default. You can use the parameter to increase or decrease the number of threads according to your server’s capabilities and workload. For example, to set the number of threads to 8, add the following line:
-t 8
Configure the idle timeout
Memcached automatically closes idle connections after a certain period of inactivity. To modify the idle timeout, use the -o parameter followed by idle_timeout and the desired number of seconds. For instance, to set the idle timeout to 600 seconds (10 minutes), add the following line:
-o idle_timeout=600
Enable SASL authentication
Enable SASL (Simple Authentication and Security Layer) support when Memcached runs on untrusted networks, shared hosting environments, or multi-tenant systems where cache isolation is required. By default, Memcached has no authentication, so anyone with network access can read and write cached data. First, install the required SASL library:
sudo apt install libsasl2-dev libsasl2-modules
Then add the SASL flag to your configuration:
-S
Remember to always restart the Memcached service after making changes to the configuration file:
sudo systemctl restart memcached
Configure UFW Firewall
If you need to access Memcached from remote hosts, configure UFW firewall rules to allow connections on port 11211. By default, Memcached only listens on localhost, so firewall rules are only required when enabling remote access. For complete UFW configuration, see our UFW installation guide for Debian. If you’re connecting remotely, ensure SSH is configured before making firewall changes.
Install and Enable UFW
First, install UFW if not already present:
sudo apt install ufw
Critical: If you are connected via SSH, allow SSH access before enabling UFW to prevent lockout.
sudo ufw allow OpenSSH
sudo ufw enable
Allow Memcached Access
Create rules to allow specific IP addresses or subnets to connect to Memcached on port 11211.
Allow access from a single IP address (replace with your application server’s IP):
sudo ufw allow proto tcp from 192.168.1.100 to any port 11211
Allow access from an entire subnet (for cluster configurations):
sudo ufw allow proto tcp from 192.168.1.0/24 to any port 11211
Verify Firewall Rules
Confirm your rules are active:
sudo ufw status numbered
Status: active
To Action From
-- ------ ----
[ 1] OpenSSH ALLOW IN Anywhere
[ 2] 11211/tcp ALLOW IN 192.168.1.100
Install Memcached Libraries
Memcached offers extensions for various programming languages, but it is most commonly used with PHP. This section covers installing Memcached client libraries for PHP, Python, and Perl, along with web server configuration for Apache and Nginx.
Install PHP Libraries for Memcached
For Apache users, install the PHP Memcached extension with mod_php. If Apache is not yet installed, see our guide on installing Apache on Debian:
sudo apt install php-memcached libapache2-mod-php php php-cli
For Nginx users, install PHP-FPM with the Memcached extension:
sudo apt install php-memcached php-fpm php php-cli
Verify the extension is loaded:
php -m | grep memcached
memcached
Configure Memcached for Apache HTTP Server
If you’re using the Apache HTTP Server, enable the Memcached module by executing the following command:
sudo phpenmod memcached && sudo systemctl restart apache2
Configure Memcached for Nginx HTTP Server
The PHP Memcached extension loads automatically once installed. However, restart PHP-FPM to ensure the new extension is active:
sudo systemctl restart php*-fpm
The wildcard pattern restarts the PHP-FPM service regardless of the installed PHP version. For complete Nginx setup instructions, see our guide on installing Nginx on Debian. Below is a sample Nginx server block configuration:
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
The PHP-FPM socket path varies by Debian version: Debian 11 uses
php7.4-fpm.sock, Debian 12 usesphp8.2-fpm.sock, and Debian 13 usesphp8.4-fpm.sock. Check your PHP version withphp -vand adjust the path accordingly.
After modifying the Nginx configuration, test and reload:
sudo nginx -t && sudo systemctl reload nginx
Install Python Library for Memcached
For Python applications requiring Memcached connectivity, install the pymemcache library:
sudo apt install python3-pymemcache
Verify the installation:
python3 -c "import pymemcache; print('pymemcache installed successfully')"
pymemcache installed successfully
Install Perl Library for Memcached
For Perl applications, install the Cache::Memcached::libmemcached module:
sudo apt install libcache-memcached-libmemcached-perl
Verify the installation:
perl -MCache::Memcached::libmemcached -e 'print "Module loaded successfully\n"'
Module loaded successfully
WordPress Object Caching with Memcached
WordPress can use Memcached for object caching, which reduces database queries by storing frequently accessed data in memory. This significantly improves page load times for high-traffic sites. For WordPress setup instructions, see our guides on installing WordPress with Nginx on Debian or installing WordPress with Apache on Debian.
To enable Memcached object caching in WordPress, install a caching plugin that supports Memcached backends:
- W3 Total Cache: Go to Performance → General Settings → Object Cache and select Memcached. Enter
127.0.0.1:11211as the server address. - LiteSpeed Cache: Navigate to LiteSpeed Cache → Cache → Object and enable Object Cache with Memcached.
- Object Cache Pro: A premium option that provides advanced Memcached integration with detailed analytics.
After configuring your caching plugin, verify that WordPress is connecting to Memcached by checking the cache statistics. First, install the netcat utility if not present:
sudo apt install netcat-openbsd
Then query the Memcached statistics:
echo "stats" | nc localhost 11211 | grep curr_items
STAT curr_items 42
If curr_items increases after browsing your WordPress site, object caching is working correctly.
Access Memcached from Command Line
Memcached can be monitored and managed through various software and web user interfaces. However, interacting directly with Memcached using the command line is often the most straightforward method for checking its performance and managing its contents.
While scripts can use nc (netcat) to query Memcached, the telnet client offers an interactive session that is more convenient for manual exploration and debugging. Install telnet if not already present:
sudo apt install telnet
Connect to your Memcached service using telnet:
telnet localhost 11211
Example output:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'.
Next, you can obtain an overview of your Memcached service with the following command:
stats
This command will return various statistics about your Memcached instance, such as uptime, the number of items in the cache, and the number of client connections.
You can refine your analysis by examining Memcached slabs (memory partitions). For example, you can list the slabs in the connected instance with:
stats slabs
And obtain a list of slabs, including a count of the items stored within each slab, using:
stats items
To access and manipulate data stored in Memcached, you can use the cachedump command to list the keys. To list all items in a specific slab, execute the following command:
stats cachedump [slab ID] [number of items, 0 for all items]
For example:
stats cachedump 1 0
Example output:
ITEM testkey [9 b; 1296857316 s] END
In this example, slab 1 contains one item with the key “testkey”. To retrieve the value of this item, use the get command:
get testkey
Example output:
VALUE testkey 0 9 test data END
Finally, to delete a cached item, such as “testkey”, use the following command:
delete testkey
Example output:
DELETED
To exit the telnet session, type quit and press Enter.
Troubleshooting Memcached
This section covers common issues you may encounter when running Memcached.
Service Fails to Start
If Memcached fails to start, check the service status for error details:
systemctl status memcached
Common causes include incorrect permissions on the configuration file or the memcache user not existing. For source-compiled installations, verify the user was created:
id memcache
Expected output if the user exists:
uid=999(memcache) gid=999(memcache) groups=999(memcache)
If you see id: 'memcache': no such user, create the user with the command from the installation section.
Connection Refused
If applications cannot connect to Memcached, verify the service is running and listening on the expected port:
ss -tlnp | grep 11211
LISTEN 0 1024 127.0.0.1:11211 0.0.0.0:* users:(("memcached",pid=1234,fd=26))
If no output appears, Memcached is not running. Check the configuration file for syntax errors and restart the service. If Memcached only listens on 127.0.0.1 but your application runs on a different host, update the -l parameter in the configuration to include the server’s IP address.
Memory Allocation Issues
Memcached evicts items when memory fills up. To check current memory usage:
echo "stats" | nc localhost 11211 | grep -E "bytes|limit_maxbytes|evictions"
High eviction counts indicate you need more memory. Increase the -m value in /etc/memcached.conf and restart the service.
Update Source-Compiled Memcached
If you installed Memcached from source, use this script to check for and apply updates. Create the update script:
sudo nano /opt/memcached-update.sh
Add the following content:
#!/bin/bash
set -e
# Check for required tools
for cmd in wget tar make gcc; do
if ! command -v $cmd &> /dev/null; then
echo "Error: $cmd is required but not installed."
exit 1
fi
done
# Check for build dependencies
if ! dpkg -l | grep -q libevent-dev; then
echo "Error: libevent-dev is required but not installed."
echo "Run: sudo apt install libevent-dev"
exit 1
fi
# Get current version
CURRENT=$(memcached -V 2>/dev/null | grep -oP '[0-9]+\.[0-9]+\.[0-9]+' || echo "none")
# Create build directory
BUILD_DIR="/opt/memcached-build"
sudo mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"
# Download latest
sudo wget -q https://memcached.org/latest -O latest.tar.gz
sudo tar -xzf latest.tar.gz
# Get downloaded version
LATEST=$(ls -d memcached-*/ | head -1 | grep -oP '[0-9]+\.[0-9]+\.[0-9]+')
echo "Current version: $CURRENT"
echo "Latest version: $LATEST"
if [ "$CURRENT" = "$LATEST" ]; then
echo "Already up to date."
sudo rm -rf "$BUILD_DIR"/*
exit 0
fi
echo "Updating to $LATEST..."
cd memcached-*/
./configure --prefix=/usr/local
make
sudo make install
sudo ldconfig
# Restart service
sudo systemctl restart memcached
echo "Updated to $(memcached -V)"
sudo rm -rf "$BUILD_DIR"/*
Make the script executable:
sudo chmod +x /opt/memcached-update.sh
Avoid automating this with cron. Compilation can fail due to missing dependencies or network issues. Always run the script manually so you can monitor the output and address problems before they affect your system.
Remove Memcached from Debian
If you need to uninstall Memcached, follow the instructions for your installation method.
Remove APT-Installed Memcached
Remove the package and clean up orphaned dependencies:
sudo apt remove --purge memcached libmemcached-tools
sudo apt autoremove
Verify the removal:
memcached -V
bash: memcached: command not found
If you previously installed Memcached from source (Method 2), the
memcached -Vcommand may still succeed because the source-compiled binary at/usr/local/bin/memcachedremains. Follow the source removal steps below to fully remove all Memcached installations.
Remove Source-Compiled Memcached
Warning: The following commands permanently delete the Memcached binary, systemd service, and build files. This cannot be undone. Ensure you no longer need the source-compiled installation before proceeding.
Stop and disable the service, then remove the installed files:
sudo systemctl stop memcached
sudo systemctl disable memcached
sudo rm /etc/systemd/system/memcached.service
sudo systemctl daemon-reload
Remove the binary and update script:
sudo rm /usr/local/bin/memcached
sudo rm -rf /opt/memcached-build
sudo rm -f /opt/memcached-update.sh
sudo rm -f /etc/memcached-local.conf
Optionally, remove the dedicated user:
sudo userdel memcache
Conclusion
You now have Memcached running on Debian with systemd service management and optional UFW firewall rules for remote access. The configuration file at /etc/memcached.conf controls memory allocation, connection limits, and network binding. For high-traffic deployments, consider increasing memory allocation beyond the default 64MB and adjusting the connection limits based on your application’s needs. If you’re integrating with a Nginx or PHP stack, the included library integrations provide the connection layer between your application code and the cache server.