Memcached is a powerful, open-source caching system designed to enhance the performance of dynamic web applications by reducing the load on databases. Developed in 2003 by Brad Fitzpatrick for the LiveJournal website, Memcached has since become an essential tool for numerous high-traffic websites and applications.
Key Features and Benefits:
- Scalability: Memcached is designed to handle millions of operations per second, making it an ideal choice for large-scale web applications and services.
- Distributed Caching: Memcached supports a distributed caching architecture, allowing for horizontal scaling across multiple servers, thus increasing the system’s overall cache capacity.
- In-Memory Storage: As an in-memory key-value store, Memcached offers rapid access to cached data, significantly reducing the latency typically associated with disk-based storage systems.
- Simple API: Memcached provides a straightforward API for developers, supporting various programming languages, including PHP, Python, Ruby, and more.
- Cache Expiration: Memcached allows developers to set expiration times for cached data, ensuring that stale or outdated data is automatically removed from the cache.
- Lightweight: With minimal CPU and memory overhead, Memcached can be efficiently deployed on various server configurations without significantly impacting system resources.
- Flexible Data Types: Memcached can store many data types, including strings, integers, and complex objects, making it a versatile caching solution for diverse use cases.
This guide will demonstrate how to install Memcached on Debian 12 Bookworm, Debian 11 Bullseye, or Debian 10 Buster using the default apt repository or manually downloading and compiling the latest sources. The article will then review some basic configuration and tips to ensure you get the most out of your Memcached installation.
Table of Contents
Section 1: Install Memcached with APT
In this section, we will go through the process of installing Memcached on your Debian Linux system using the APT package manager. This involves updating your system packages and then installing Memcached along with some helpful tools.
Step 1: Update Your Debian System
To ensure that you have the latest package versions and security updates, start by updating your Debian system. Run the following command:
sudo apt update && sudo apt upgrade
This command will update your package list and upgrade any outdated packages to their latest versions.
Step 2: Install Memcached and Libmemcached-tools
Debian includes Memcached in its default repositories, making installation simple. To install Memcached, run the following command:
sudo apt install memcached libmemcached-tools
This command installs both Memcached and the libmemcached-tools
package. The libmemcached-tools
package provides additional command-line utilities that enable more interaction and management capabilities with Memcached.
Section 2: Install Memcached with Source
This section covers the process of 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 need to customize the build for specific requirements.
Step 1: Download the Memcached Source
First, visit the Memcached latest release page to find the current version. Use the following wget
command to download it directly:
wget https://memcached.org/latest
Step 2: Extract the Source Code
Next, extract the downloaded source code by running the following command:
tar -xvf latest
Before you continue, navigate to the extracted directory. The directory name depends on the downloaded version:
cd memcached-{place version number here}
Replace {version_number}
with the actual version number.
Step 3: Install the Required Packages
Before compiling Memcached, you need to install the necessary build dependencies. Run the following command to install them:
sudo apt install build-essential libevent-dev gcc make libc6-dev
The installed packages serve the following purposes:
gcc
: A well-known C compiler for the Memcached source files.make
: Directs compilation.libc6-dev
: Provides a reference to the GNU C library and header files.libevent-dev
: Contains development files for asynchronous event notification.
Step 4: Configure the Installation
Use the --prefix=
parameter to set the directory where Memcached binary and libraries will be installed:
./configure --prefix=/usr/local
Step 5: Compile the Source Code
Compile the Memcached source code with the make
command:
make
Test Memcached by confirming the current version:
./memcached --version
Step 6: Install Memcached
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
Step 7: Verify the Installation
To verify that Memcached is successfully installed, run the following command:
memcached -V
This command will display the installed Memcached version, confirming the successful installation from the source code.
Step 8: Creating a Systemd Service for Memcached
When you install Memcached from source, it does not automatically create a systemd service file. To run Memcached as a service and manage it using systemctl
, you need to create a custom systemd service file for Memcached. Follow these steps to create and enable the service:
Create a new file called memcached.service
in the /etc/systemd/system
directory using a text editor of your choice. In this example, we’ll use nano
:
sudo nano /etc/systemd/system/memcached.service
Add the following content to the memcached.service
file:
[Unit]
Description=Memcached Service
After=network.target
[Service]
Type=simple
User=memcache
Group=memcache
ExecStart=/usr/local/bin/memcached /etc/memcached.conf
Restart=always
[Install]
WantedBy=multi-user.target
Save the file and exit the text editor.
Create a memcache
user and group to run the service securely:
sudo useradd -r -s /sbin/nologin -U -M memcache
Reload the systemd configuration to recognize the new service file:
sudo systemctl daemon-reload
Lastly, start the service:
sudo systemctl enable memcached --now
Section 3: Managing Memcached Service Status
This section will cover managing the Memcached service on your Debian system. This includes checking the service status, starting and stopping the service, and configuring it to run at system boot.
Step 1: 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.
Step 2: Start the Memcached Service
If Memcached is not running, you can start the service with the following command:
sudo systemctl start memcached
Step 3: Enable Memcached on System Boot
To ensure that the Memcached service starts automatically when your system boots, use the following command:
sudo systemctl enable memcached
Step 4: Stop the Memcached Service
If you need to stop the Memcached service, use this command:
sudo systemctl stop memcached
Step 5: Disable Memcached on System Boot
To prevent the Memcached service from starting automatically at system boot, run the following command:
sudo systemctl disable memcached
Step 6: 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
Step 7: Verify Memcached is Listening on the Default Port
Lastly, verify that Memcached is actively listening on the localhost using the default port 11211
. To confirm this, run the following command:
ps -ef | grep memcached
The output should display a line indicating that Memcached is running and listening on the specified port, similar to the following:
memcache 5934 1 0 09:36 ? 00:00:00 /usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1 -P /var/run/memcached/memcached.pid
root 6591 3653 0 09:55 pts/0 00:00:00 grep memcached
Section 4: Configuring Memcached
This section will cover how to configure the Memcached settings by editing the memcached.conf
file. We will discuss adjusting the listening IP address, disabling UDP, and changing the default memory allocation.
Step 1: Open the Memcached Configuration File
Open the Memcached configuration file located at /etc/memcached.conf
using a text editor, such as nano
:
sudo nano /etc/memcached.conf
Users that compiled Memcached from source will need to create this so when you first open it the file will be blank compared to the APT method, you can copy this to get started for adjusting:
# Example memcached.conf file
# Start with a cap of 64 megs of memory. It's reasonable, and the daemon default
# Note that the daemon will grow to this size, but does not start out holding this much
# memory
-m 64
# Default port is 11211
-p 11211
# Run the daemon as a background process
-d
# Use syslog logging
-s
# Enable verbose logging
-vv
# Set the maximum number of simultaneous connections
-c 1024
Step 2: Adjust the Listening IP Address
By default, Memcached listens on IP address 127.0.0.1
. Check the -l
parameter in the configuration file and make sure 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
Step 3: Disable UDP (Optional)
If you don’t require UDP support, it is recommended to disable it. To disable UDP, add the following line to the configuration file:
-U 0
Step 4: Configure the Memory Allocation
The default memory allocation for Memcached is 64MB, which may not be sufficient for larger websites. To make the most of Memcached, consider adjusting the memory allocation to a higher value.
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 2000
:
-m 2000
Adjust this setting based on your server’s available memory and requirements.
Step 5: Save and Restart Memcached
After making the necessary changes, save the configuration file by pressing CTRL+O
, followed by Y
, and then CTRL+X
to exit the text editor. Finally, restart the Memcached service for the changes to take effect:
sudo systemctl restart memcached
Additional Configuration Examples
Here are some other common configuration options you might consider:
In addition to the configuration options covered earlier, there are several other settings that you can adjust to fine-tune Memcached according to your requirements. Here are some examples, along with brief demonstrations:
Specify the user and group: Memcached runs under a specific user and group, which are 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: If your system supports large memory pages, enabling this feature may improve performance. 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 1MB. 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: By default, Memcached uses four threads. You can increase or decrease the number of threads according to your server’s capabilities and workload by using the -t
parameter. 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: If you require authentication to access your Memcached server, you can enable SASL (Simple Authentication and Security Layer) support. To enable SASL, find the -S
parameter and uncomment it (remove the #
at the beginning of the line):
-S
Remember to always restart the Memcached service after making changes to the configuration file:
sudo systemctl restart memcached
Section 5: Installing and Configuring UFW for Memcached Security
To ensure the security of your Memcached instance, it is crucial to configure your firewall rules properly. This section will cover how to install and configure the Uncomplicated Firewall (UFW) to secure your Memcached server.
Step 1: Check if UFW is installed
First, let’s verify if UFW is already installed on your Debian system:
sudo ufw --version
If UFW is installed, you will see its version number in the output. If not, you’ll need to install it.
Step 2: Install UFW
To install UFW on your Debian system, run the following command:
sudo apt install ufw
After the installation is complete, enable UFW with the following command:
sudo ufw enable
Step 3: Configure UFW rules for Memcached
Now that UFW is installed and enabled, you need to create allow rules on TCP port 11211. The specific rules you create will depend on your installation and requirements, whether you’re using a single IP network connection or working with multiple instances in a cluster network.
Single IP network connection example:
Allow access to Memcached from a specific IP address:
sudo ufw allow proto tcp from <ip_address> to any port 11211
Cluster IP network connection with multiple instances example:
Allow access to Memcached from a subnet of IP addresses:
sudo ufw allow proto tcp from <ip_address>/24 to any port 11211
Note that the second UFW rule is a subnet rule. Ensure that the internal network is secure and trustworthy before allowing access.
Step 4: Verify UFW rules
After setting up the appropriate rules, verify that they are correctly configured by listing the current UFW rules:
sudo ufw status
The output should display your configured rules, ensuring that your Memcached instance is secured with UFW.
Section 6: Installing Memcached Libraries for Various Programming Languages
Memcached offers extensions for various programming languages, but it is most commonly used with PHP. In this section, we will guide you through installing Memcached libraries for PHP, Python, and Perl, as well as configuring Memcached for Apache and Nginx web servers.
Step 1: Install PHP Libraries for Memcached
To install the PHP library for Memcached, run the following command:
sudo apt install php-memcached libapache2-mod-php php php-cli
Step 2: 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
Step 3: Configure Memcached for Nginx HTTP Server
For Nginx users, Memcached support will be enabled by default within your PHP configuration block once the PHP library is installed.
Example block:
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/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Step 4: Install Python Library for Memcached
To install Python support for Memcached, run the following command:
sudo apt install python3-pymemcache
Step 5: Install Perl Library for Memcached
To install Perl support for Memcached, execute the following command:
sudo apt install libcache-memcached-libmemcached-perl
Section 7: Accessing 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.
First, 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 further refine your analysis by examining the different 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
Conclusion: Installing Memcached on Debian Linux
In conclusion, installing and configuring Memcached on Debian Linux can significantly improve the performance of your web applications by providing a fast, efficient, and easy-to-use caching system. Following the steps outlined in this guide, you can successfully set up Memcached, configure it with your preferred web server, and secure it using UFW. With the right configuration and management, Memcached can become essential in optimizing your applications and providing a better user experience.
Additional Resources and Links
To further enhance your understanding of Memcached and expand your knowledge, the following official resources and links are recommended:
- Memcached Official Website: Learn more about Memcached, its features, and its uses from the official website.
- Memcached GitHub Repository: Explore the source code and contribute to the Memcached project on GitHub.
- Memcached Documentation: Access the official documentation and guides on the Memcached wiki to dive deeper into its capabilities and configuration options.
- Debian Official Website: Find information about the Debian Linux distribution, including guides, documentation, and support resources.
- Debian Wiki: Explore the Debian Wiki for more in-depth information about Debian, including package management, system administration, and configuration tips.