How to Install Memcached on Debian 12, 11 or 10

Brad Fitzpatrick developed Memcached in 2003 for the LiveJournal website as a powerful, open-source caching system to enhance the performance of dynamic web applications by reducing database load. Since then, it has become vital for many high-traffic websites and applications. Before we dive into the installation of Memcached on Debian 12 Bookworm, Debian 11 Bullseye, or Debian 10 Buster, let’s examine some key points about Memcached below.

Key Features and Benefits:

  • Scalability: Memcached, handling millions of operations per second, is ideal for large-scale web applications and services.
  • Distributed Caching: With a distributed caching architecture, Memcached allows horizontal scaling across multiple servers, expanding overall cache capacity.
  • In-Memory Storage: As an in-memory key-value store, Memcached ensures rapid access to cached data, significantly decreasing latency in disk-based storage systems.
  • Simple API: Memcached provides a straightforward API that supports various programming languages, including PHP, Python, Ruby, and others.
  • Cache Expiration: The system enables developers to set expiration times for cached data, facilitating the automatic removal of outdated or stale data from the cache.
  • Lightweight: With minimal CPU and memory overhead, Memcached efficiently runs on various server configurations without significantly draining system resources.
  • Flexible Data Types: Accommodating various data types such as strings, integers, and complex objects, Memcached is versatile for diverse use cases.

The following guide will walk you through the installation process of Memcached on Debian 12 Bookworm, Debian 11 Bullseye, or Debian 10 Buster using either the default apt repository or manually downloading and compiling the latest sources. After installation, the article will offer essential configuration tips and tricks to help you optimize your Memcached installation.

Install Memcached on Debian 12, 11, or 10 via APT

In this section, we will install Memcached on your Debian Linux system using the APT package manager. This involves updating your system packages and installing Memcached with some helpful tools.

Step 1: Update Your Debian System Before Memcached Installation

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 outdated packages to their latest versions.

Step 2: Install Memcached and Libmemcached-tools on Debian

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.

Install Memcached on Debian 12, 11, or 10 via source

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.

Step 1: Download the Memcached Source on Debian

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 Memcached source archive on Debian

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 Initial Packages Required to Compile Memcached

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 Memcached Source Code on Debian

Compile the Memcached source code with the make command:

make

Test Memcached by confirming the current version:

./memcached --version

Step 6: Install Memcached on Debian via ‘make install’ command

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 of Memcached on Debian

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: Create a Systemd Service for Memcached on Debian

When you install Memcached from the 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

Managing Memcached Service Status on Debian 12, 11, or 10

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 the 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 the 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

Configure Memcached on Debian 12, 11, or 10

This section will cover configuring 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 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

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. 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 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 Memcached Configuration Examples with Debian

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 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

You can enable SASL (Simple Authentication and Security Layer) support if you require authentication to access your Memcached server. 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

Install UFW Firewall for Memcached on Debian 12, 11, or 10

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 on Debian

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 on Debian for Memcached

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 on Debian

Now that UFW is installed and enabled, you must create allow rules on TCP port 11211. The rules you create will depend on your installation and requirements, whether 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 your Memcached instance is secured with UFW.

Install Memcached Libraries on Debian 12, 11 or 10

Memcached offers extensions for various programming languages, but it is most commonly used with PHP. This section will guide you through installing Memcached libraries for PHP, Python, and Perl and configuring Memcached for Apache and Nginx web servers.

Install PHP Libraries for Memcached on Debian

To install the PHP library for Memcached, run the following command:

sudo apt install php-memcached libapache2-mod-php php php-cli

Configure Memcached for Apache HTTP Server on Debian

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 on Debian

Memcached support will be enabled by default within your PHP configuration block once the PHP library is installed for Nginx users.

Below is a simple nginx server block example:

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;
    }
}

Install Python Library for Memcached on Debian

To install Python support for Memcached, run the following command:

sudo apt install python3-pymemcache

Install Perl Library for Memcached on Debian

To install Perl support for Memcached, execute the following command:

sudo apt install libcache-memcached-libmemcached-perl

Access Memcached from Command Line on Debian 12, 11, or 10

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 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

Conclusion

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 proper configuration and management, Memcached can become essential in optimizing your applications and providing a better user experience.

Leave a Comment