Memcached is a high-performance distributed memory caching system that primarily speeds up dynamic web Memcached is a high-performance, distributed memory caching system used to speed up dynamic web applications by reducing database load. It stores data in memory, which allows for quick retrieval, making it an essential tool for applications that require fast access to frequently used data. Memcached is commonly used in environments where performance and scalability are critical, such as large-scale web applications and services.
On Ubuntu 24.04, 22.04, or 20.04, Memcached can be installed using two primary methods via the command-line terminal. The first method is using the Ubuntu default repository, which provides a stable and straightforward installation of Memcached. For users who require the latest version with the most recent features and performance improvements, the second method involves downloading and compiling the latest binary build from the official Memcached source. This guide will walk you through both installation methods, ensuring you can choose the approach that best suits your needs.
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 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.
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:
make
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:
[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 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
-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 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:
-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
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;
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
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:
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
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]
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
With Memcached installed on your Ubuntu system, you can significantly enhance the performance of your web applications by reducing database load and improving data retrieval times. Whether you choose the convenience of the Ubuntu default repository or the flexibility of compiling the latest binary build, both methods provide you with a robust caching solution. Regularly updating Memcached, particularly if you compile from source, will ensure you have access to the latest optimizations and features, keeping your caching system efficient and up-to-date.