How to Install Memcached on Ubuntu 24.04, 22.04 or 20.04

This guide will demonstrate how to install Memcached on Ubuntu versions 24.04, 22.04, or 20.04. It will detail the method of installing via Ubuntu’s default APT repository and the alternative approach of downloading, extracting, compiling, and installing the latest Memcached from the source tarball directly onto your Ubuntu server.

Memcached, a powerful and high-performance distributed memory caching system, primarily speeds up dynamic web applications by reducing database load. It caches data and objects in RAM, thereby minimizing the frequency of reading 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: Offers a simplistic yet robust in-memory key-value store for small chunks of arbitrary data (strings, objects) from 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: Compatible with a wide range of 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 main part of our how-to article, let’s dive into the Memcached installation on Ubuntu Linux.

Table of Contents

Install Memcached on Ubuntu via APT

Update Ubuntu Before Installing Memcached

Prioritize updating your Ubuntu package index to ensure its current state before you proceed with the Memcached installation via APT. 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 on Ubuntu 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.

Install Memcached on Ubuntu via source

This section will offer an alternative method to install Memcached on Ubuntu via source. Opting for this installation method is particularly advantageous if your use case necessitates the latest version of Memcached or needs 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:

wget https://memcached.org/latest

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.

Extracting Memcached source files on Ubuntu Linux
Detailed view of the extraction process of Memcached source files on Ubuntu Linux

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
Configure command output for Memcached build on Ubuntu Linux
Terminal output of the configure command for Memcached build on Ubuntu Linux

Compile the Memcached Source Code

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

make
Make build completion for Memcached on Ubuntu Linux
Terminal view of the successful make build for Memcached on Ubuntu Linux

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.

Memcached installed via compiled binary with version check on Ubuntu Linux
Confirming Memcached installation and version on Ubuntu Linux

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:

[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

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

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

For security purposes, running services with a dedicated user and group is best practice. 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 on Ubuntu

When working with Memcached on Ubuntu, it’s crucial to ensure that your service is configured correctly and running as expected. This section provides a step-by-step walkthrough of how to manage the Memcached service, verify its status, and interact 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
Memcached systemd service enabled on Ubuntu Linux
Systemd service configuration for Memcached on Ubuntu Linux

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 is actively listening 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.

Checking listening ports for Memcached on Ubuntu Linux
Terminal output showcasing Memcached listening ports on Ubuntu Linux

Configure Memcached on Ubuntu

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

# Use syslog logging
-s

# Enable verbose logging
-vv

# 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 127.0.0.1. 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 127.0.0.1 with your preferred IP address.

-l 127.0.0.1

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 the available memory and requirements of your server.

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

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, adjustable using the -u parameter. For instance, to run Memcached as the memcache user, incorporate the following line:

-u memcache

Enable Large Memory Pages

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

-L

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:

-S

Ensure you restart the Memcached service after any configuration changes:

sudo systemctl restart memcached

Secure Memcached with UFW on Ubuntu

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

For setups involving multiple instances in a cluster network, you might need to allow access from a range of IP addresses. 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 it’s crucial to ensure that your internal network is secure and trustworthy before implementing this rule.

Confirm UFW Configuration

After setting up the rules, confirming they have been correctly configured is important. 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 on Ubuntu

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 the process of 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 on Ubuntu

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

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

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

Lastly, to enable Memcached support for Perl, execute:

sudo apt install libcache-memcached-libmemcached-perl

Accessing Memcached via Command Line on Ubuntu

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:

Trying 127.0.0.1...
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:

stats

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

For managing 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]
END

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
END

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:

DELETED

Conclusion

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. Remember, 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.

For those who seek more information, a suggestion would be to visit the Memcached Wiki.

Leave a Comment


Your Mastodon Instance
Share to...