How to Install Memcached on Ubuntu 24.04, 22.04, or 20.04

Memcached is a high-performance distributed memory caching system that primarily speeds up dynamic web applications by reducing database load. It caches data and objects in RAM, minimizing the reading frequency from external data sources, such as databases or APIs.

Below are some key features that make Memcached an essential tool for modern web development:

  • Efficient Caching: Memcached offers a simplistic yet robust in-memory key-value store for small chunks of arbitrary data (strings, objects) retrieved from the results of database calls, API calls, or page rendering.
  • High Scalability: Easily scales horizontally, allowing multiple servers to form part of a single cache, making it ideal for high-traffic websites and large-scale web applications.
  • Flexibility and Compatibility: It is compatible with various programming languages and platforms, ensuring seamless integration with various application stacks.
  • Speed and Performance Optimization: Significantly improves the response time of websites and applications by reducing the burden on the database through efficient data retrieval mechanisms.
  • Simple Design: Its straightforward design and ease of deployment allow for quick setup and minimal maintenance.

Moving on to the central part of our how-to article, let’s dive into the Memcached installation on Ubuntu. This will cover terminal commands to install Memcached via the Ubuntu repository, which is the most common method, or to download and install the latest source archive version for those who do not mind manually upgrading to have the latest built version on their system.

Prerequisites for Installing Memcached

To successfully install Memcached on Ubuntu, ensure you meet the following requirements:

System Requirements and Supported Ubuntu Versions

Processor2 gigahertz (GHz) or faster dual-core processor
RAM4 GB or more
Disk Space25 GB of free space
NetworkBroadband internet connection
Supported VersionsUbuntu 24.04 (Noble), Ubuntu 22.04 (Jammy), Ubuntu 20.04 (Focal)

Additional Requirements

Internet ConnectionRequired to download Memcached and updates.
Terminal ConventionsAll terminal commands should be run as a regular user with sudo privileges.
CLI CommandsUse the Command Line Interface (CLI) for installation and setup.
Network ConfigurationEnsure proper network configuration to allow Memcached communication.

Method 1: Install Memcached via APT

Update Ubuntu Before Installing Memcached

Update your Ubuntu package index to ensure its current state before proceeding with the Memcached installation via APT. Also, make it a priority to process any pending system upgrades, creating a smooth pathway for the Memcached installation.

Prefer: Execute the update command below:

sudo apt update

Follow this up by upgrading any outdated packages with the command:

sudo apt upgrade

Install Memcached via APT Command

Ubuntu’s repositories include Memcached, and this version generally meets the needs of most Ubuntu applications. Thus, it comes highly recommended as the primary installation choice.

To install Memcached and the “libmemcached-tools” package (which adds extra functionalities and command options to interact with Memcached), input the following command:

sudo apt install memcached libmemcached-tools 

Confirm Memcached Installation via APT

Finally, ensure the successful installation of Memcached by checking its version with the following command:

memcached --version

By doing this, you confirm that Memcached is ready to use on your Ubuntu system.

Method 2: Install Memcached via source

This section will offer an alternative method for installing Memcached on Ubuntu via source. This installation method is particularly advantageous if your use case necessitates the latest version of Memcached or if you need to tailor the build to meet specific needs.

Fetch the Memcached Source

Initiate this process by navigating to the official release page of Memcached to pinpoint the most recent version. Employ the wget command to download it straight to your system seamlessly:


Unpack the Memcached Source Archive

Proceed to extract the recently downloaded source code with the following command:

tar -xvf latest

Here, replace {version_number} with the actual version number you’ve acquired.

Prepare for Compilation by Installing Dependencies

Before embarking on the compilation of Memcached, it’s pivotal to install essential build dependencies. Execute the following command to achieve this:

sudo apt install build-essential libevent-dev gcc make libc6-dev

A brief overview of the installed packages and their roles:

  • gcc: An indispensable C compiler essential for processing Memcached’s source files.
  • make: Facilitates and directs the compilation process.
  • libc6-dev: Offers access to the GNU C library and pertinent header files.
  • libevent-dev: Provides necessary development files for asynchronous event notification.

Configure the Installation Setup

First, navigate to the folder that you just extracted:

cd memcached-x.x.x

Next, utilize the --prefix= parameter to explicitly specify the directory where you intend to install the Memcached binaries and libraries:

./configure --prefix=/usr/local

Compile the Memcached Source Code

Engage in compiling the Memcached source code by invoking the make command:


You can validate the current version of Memcached to ensure everything is proceeding as expected:

./memcached --version

Finalize Installation with the ‘make install’ Command

With the compilation completed, proceed to install Memcached using the following command:

sudo make install

Confirm Memcached Installation via source method

Ensure the installation is successful by running the following:

memcached -V

This command should return the version number, affirming that Memcached has been installed correctly from the source.

Setting Up a Systemd Service for Memcached

After successfully installing Memcached on your Ubuntu system, the next crucial step is to ensure it operates as a service, allowing you to manage it efficiently using systemctl. This requires creating a systemd service file specifically for Memcached.

Creating the Service File

To get started, open your text editor with administrative privileges. Here, we’ll use nano for its simplicity:

sudo nano /etc/systemd/system/memcached.service

In the opened file, input the following configuration:

Description=Memcached Service

ExecStart=/usr/local/bin/memcached /etc/memcached.conf


This configuration outlines how the Memcached service should operate, ensuring it starts after running the network.

Saving and Closing the Text Editor

Once you’ve inputted the configuration, save your changes and exit the text editor. If you’re using Nano, you can do this by pressing CTRL + X, then Y to confirm the changes, and finally Enter to close.

Creating a User and Group for Memcached

Running services with a dedicated user and group is best practice for security purposes. Execute the following command to create a user and group both named memcache:

sudo useradd -r -s /sbin/nologin -U -M memcache

This command ensures the memcache user has no login shell and creates a group with the same name.

Reloading the Systemd Configuration

With all configurations set, the final step is to reload the systemd manager configuration. This makes sure systemd recognizes the newly created Memcached service file:

sudo systemctl daemon-reload

Memcached Service Commands

When working with Memcached on Ubuntu, ensuring that your service is configured correctly and running as expected is crucial. This section provides a step-by-step walkthrough of managing the Memcached service, verifying its status, and interacting with it through various commands.

Checking the Status of the Memcached Service

Memcached should automatically be up and running upon installation. To confirm its status, execute the following command:

systemctl status memcached

If, for any reason, Memcached is not active, you can initiate the service and ensure it starts automatically upon system boot with the following command:

sudo systemctl enabled memcached --now

Additional Memcached Service Commands

Familiarizing yourself with various service commands is vital for efficient Memcached management. Below are some of the key commands:

Start Memcached within the current user session:

sudo systemctl start memcached

Set Memcached to automatically start at system boot:

sudo systemctl enable memcached

Stop the Memcached service:

sudo systemctl stop memcached

Prevent Memcached from starting automatically at system boot:

sudo systemctl disable memcached

Restart Memcached:

sudo systemctl restart memcached

These commands provide a solid foundation for managing the Memcached service and ensuring it’s running according to your preferences.

Confirming Memcached’s Active Listening Port

Verifying that Memcached actively listens to the local host on its default port, 11211, is essential. You can do this by running:

ps -ef | grep memcached

This command lists all services listening on the specified port, helping you ensure that Memcached is running and ready to handle requests.

Quick Rundown on Configuring Memcached

This segment delves into the configuration of Memcached settings, focusing on the editing of the memcached.conf file. The discussion includes details on adjusting the listening IP address, disabling UDP, and altering the default memory allocation.

Accessing the Memcached Configuration File

To start, access the Memcached configuration file found at /etc/memcached.conf using a text editor of your choice, such as Nano.

You can do this by running the command:

sudo nano /etc/memcached.conf

For users who have compiled Memcached from source, it’s crucial to note that this file will initially be blank. Unlike the APT method, you’ll need to populate the file manually. Below is an example memcached.conf file to help you get started:

# 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

# Use syslog logging

# Enable verbose logging

# Set the maximum number of simultaneous connections
-c 1024

Configuring the Listening IP Address

Memcached, by default, is set to listen to the IP address You should verify the -l parameter in your configuration file to ensure it’s set to the correct IP address for your needs. To change the IP address, replace with your preferred IP address.


Disabling UDP (Optional)

Disabling UDP is recommended if you don’t require its support. To do this, add the following line to your configuration file:

-m 2000

Adjusting Memory Allocation

The default memory allocation for Memcached is set at 64MB, which might not be adequate for larger websites. You should consider adjusting this to a higher value to optimize Memcached’s performance. Locate the -m parameter in the configuration file and replace the default value with your required amount (in MB). For instance, to allocate 2GB of memory, set the value to 2000:

-m 2000

Ensure this setting is adjusted according to your server’s available memory and requirements.

Saving Changes and Restarting Memcached

Once all necessary adjustments have been made, save the configuration file. If you’re using nano, press CTRL+O, confirm with Y, and exit with CTRL+X. To apply the changes, restart the Memcached service:

sudo systemctl restart memcached

Additional Configuration Tips for Memcached

Beyond the basic settings, there are a variety of additional parameters you can configure to fine-tune Memcached to suit your needs better.

Here are some examples and brief explanations:

Specify User and Group

Memcached operates under specified user and group settings and is adjustable using the -u parameter. For instance, to run Memcached as the memcache user, incorporate the following line:

-u memcache

Enable Large Memory Pages

Enabling this feature might enhance performance if your system supports large memory pages. Find the -L parameter and uncomment it:


Configure Maximum Item Size

By default, Memcached has a 1 MB limit for item size. To increase this, use the -I parameter followed by your desired size. For a 5MB item size, for example, add:

-I 5m

Set the Maximum Number of Threads

Memcached defaults to four threads, but this can be adjusted to suit your server’s capabilities and workload. To set the number of threads to eight, add:

-t 8

Adjust Idle Timeout

Memcached automatically closes connections after inactivity, adjustable with the -o parameter. For a 600-second timeout, include:

-o idle_timeout=600

Enable SASL Authentication

For those requiring authentication to access the Memcached server, enable SASL (Simple Authentication and Security Layer) support by uncommenting the -S parameter:


Ensure you restart the Memcached service after any configuration changes:

sudo systemctl restart memcached

Secure Memcached with UFW

Securing your Memcached instance is crucial to protect your data and maintain the integrity of your system. In this guide, we will walk through installing and configuring the Uncomplicated Firewall (UFW) on an Ubuntu system, ensuring a secure environment for your Memcached server.

Verify UFW Installation on Ubuntu

Before proceeding with the configuration, checking whether UFW is installed on your Ubuntu system is essential. You can do this by running the command:

sudo ufw --version

If UFW is installed, the version number will be displayed in the output. If it’s not installed, you must proceed to the next step to install it.

Install UFW for Memcached

If UFW is not present on your system, you can install it by executing the following command:

sudo apt install ufw

Once the installation is complete, activate UFW using:

sudo ufw enable

Set Up UFW Rules for Memcached

With UFW installed and active, the next step is configuring the firewall rules to secure your Memcached server. The rules you need to create will depend on your specific setup and requirements. Below are examples of a single IP network connection and a cluster network with multiple instances.

Single IP Network Connection

If you’re connecting from a specific IP address, you can allow access to Memcached with the following command:

sudo ufw allow proto tcp from <ip_address> to any port 11211

Replace <ip_address> with the actual IP address from which you’ll be connecting.

Cluster Network with Multiple Instances

You might need to allow access from a range of IP addresses for setups involving multiple instances in a cluster network. Here’s how you can do it:

sudo ufw allow proto tcp from <ip_address>/24 to any port 11211

Make sure to replace <ip_address> with the appropriate subnet address. Note that this is a subnet rule, and ensuring your internal network is secure and trustworthy before implementing it is crucial.

Confirm UFW Configuration

After setting up the rules, it is important to confirm they have been correctly configured. You can list the current UFW rules with:

sudo ufw status

The output will display the rules you’ve configured, allowing you to verify that your Memcached instance is now secured with UFW. Ensure that all settings are correct and aligned with your network requirements.

Install Memcached Libraries

Memcached is widely recognized for its ability to enhance performance by caching data and objects in RAM to reduce the load on databases. While it supports various programming languages, its integration with PHP is notably prevalent. In this guide, we will walk through installing and configuring Memcached libraries for PHP, Python, and Perl and setting it up with Apache and Nginx web servers.

Setting up PHP Libraries for Memcached

Installing PHP Libraries for Memcached

Begin by installing the PHP library for Memcached. Execute the command below in your terminal:

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

This command installs the necessary PHP Memcached library and associated modules, ensuring that your system can interface with Memcached using PHP.

Configuring Memcached for Apache HTTP Server

Should you choose Apache as your web server, the next step involves enabling the Memcached module. You can achieve this by running:

sudo phpenmod memcached && sudo systemctl restart apache2

This command activates the Memcached module and restarts the Apache server to apply the changes.

Setting up Memcached with Nginx HTTP Server

For those utilizing Nginx, Memcached support becomes available by default in your PHP configuration block upon installing the PHP library. Below is a basic example of an Nginx server block:

server {
    listen 80;

    root /var/www/;
    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;

This configuration ensures your Nginx server is properly set up to interact with Memcached through PHP.

Integrating Memcached with Other Programming Languages

Installing Python Library for Memcached

To extend Memcached support to Python, run the following installation command:

sudo apt install python3-pymemcache

This command ensures the necessary Python library for interfacing with Memcached is installed.

Installing Perl Library for Memcached

Lastly, to enable Memcached support for Perl, execute:

sudo apt install libcache-memcached-libmemcached-perl

Accessing Memcached via Command Line

Memcached is a versatile tool capable of being monitored and administered through various interfaces, including software and web-based UIs. Yet, one of the most direct and uncomplicated methods to interact with Memcached is through the command line, providing immediate insights into its performance and the ability to manage its content efficiently.

Establishing a Connection to Memcached

To begin, establish a connection to your Memcached service using the telnet command:

telnet localhost 11211

Upon successful execution, you should see an output similar to the following:

Connected to localhost.
Escape character is '^]'.

Install Telnet using the following command if it is not installed.

sudo apt install telnet

Retrieving Memcached Statistics

Following the connection, retrieve a comprehensive overview of your Memcached service with the stats command:


This command will provide various statistics pertinent to your Memcached instance, ranging from uptime and cache item count to the number of active client connections.

Analyzing Memory Partitions

To delve deeper into the memory allocations of Memcached, analyze the slabs (memory partitions) with:

stats slabs

Additionally, acquire a detailed list of slabs, inclusive of the item count within each, through:

stats items

Managing Cached Data

To manage the data stored in Memcached, utilize the cachedump command to display the keys. To list all items within a specific slab, the following command structure is utilized:

stats cachedump [slab ID] [number of items, 0 for all items]

For instance:

stats cachedump 1 0

This command’s execution will present an output akin to:

ITEM testkey [9 b; 1296857316 s]

In this example, slab 1 encompasses a single item identified by the key “testkey”. To fetch the value associated with this item, employ the get command:

get testkey

The output for this command should resemble the following:

VALUE testkey 0 9
test data

Deleting Cached Items

To conclude, should you wish to delete a cached item, such as “testkey”, the delete command is at your disposal:

delete testkey

The system should confirm the deletion with the following:



There you have it! We’ve journeyed through the straightforward steps of installing Memcached on your Ubuntu Linux 24.04, 22.04, or 20.04 server, covering both the APT repository method and the manual source compilation. Keeping your Memcached version up-to-date is key for performance and security, so don’t hesitate to revisit these steps for updates. Finally, enjoy the speed and efficiency boost Memcached brings to your applications.

Useful Links

Here are some valuable links related to using Memcached:

  • Memcached Official Website: Visit the official Memcached website for information about the distributed memory caching system, its features, and download options.
  • Memcached GitHub Repository: Access the Memcached GitHub repository to view the source code, report issues, and contribute to the development.
  • Memcached Wiki: Explore the Memcached Wiki for comprehensive documentation, tutorials, and user guides.
  • Memcached GitHub Issues: Join the discussion on GitHub to report issues, track bugs, and view feature requests for Memcached.
Joshua James
Follow me
Latest posts by Joshua James (see all)