How to Install and Configure Memcached on Ubuntu?


Written by - Deepak Prasad

This tutorial will guide you through detailed steps to install and configure Memcached on Ubuntu. We'll cover the installation process, setting up the configuration file, managing the Memcached service, connecting it with different programming languages, securing the setup

Memcached is a free and open-source high-performance in-memory key-value store primarily used for caching data. It's a powerful tool designed to speed up dynamic web applications by alleviating the database load. Memcached operates by storing data in memory, which includes various objects and results from database calls, API calls, or page rendering. The in-memory nature of Memcached allows for extremely fast data retrieval, significantly reducing the time applications spend accessing data stored on disk or within a database. This results in faster loading times and a more responsive application performance, making Memcached an essential component in optimizing and scaling modern web applications. Memcached is widely used in various environments, particularly those with high data read requirements, such as busy websites, to improve user experience and system efficiency.

 

1. Steps to install Memcached in Ubuntu

1.1 Open the Terminal

You can do this by searching for 'Terminal' in your applications menu or pressing Ctrl + Alt + T. In my cases since I had also installed Terminator Terminal, hence that is shown as an additional option.

How to Install and Configure Memcached on Ubuntu?

 

1.2 Update the Package List

Before installing new software, it's good practice to update your package list. This ensures you have the latest versions of packages and dependencies. This command must be executed using sudo privilege:

sudo apt update

 

1.3 Install Memcached

With your package list updated, install Memcached by executing the following apt command:

sudo apt install -y memcached
How to Install and Configure Memcached on Ubuntu?

 

1.4 Install libmemcached-tools

This package provides utilities for managing the Memcached server from the command line. Install it using:

sudo apt install -y libmemcached-tools
How to Install and Configure Memcached on Ubuntu?

 

1.5 Verify the Installation

After installing, you can check the status of the Memcached service to ensure it's running properly:

sudo systemctl status memcached
How to Install and Configure Memcached on Ubuntu?

If the service is active, it should display active (running) in the terminal output.

If it is not in running state, then you can start the same using

sudo systemctl start memcached

Make sure the service is configured to auto start after reboot:

$ sudo systemctl is-enabled memcached
enabled

If this is disabled then you can enable the same using

sudo systemctl enable memcached

These steps will install Memcached on your Ubuntu system and get the service up and running. Memcached is a daemon that runs in the background, so once it's installed and started, it's ready to be used or configured further according to your requirements. Remember, after installation, Memcached is configured to listen only on localhost by default. If you need to change this setting, you'll need to modify the Memcached configuration file (/etc/memcached.conf), especially if you're planning to allow remote connections.

 

2. Configuring Memcached

Configuring Memcached on Ubuntu involves editing the /etc/memcached.conf file, which is the primary configuration file for Memcached. This file allows you to set various parameters that control how Memcached operates. Here’s a step-by-step guide to configuring Memcached:

 

2.1 Open the Configuration File

Use a text editor to open the Memcached configuration file. You can use nano or any editor of your choice:

sudo nano /etc/memcached.conf

 

2.2 Set Memcached to Listen on localhost (Default)

  • By default, Memcached is configured to listen only on localhost (127.0.0.1). This setting is ideal for local applications that run on the same server as Memcached.
  • Look for the line starting with -l 127.0.0.1 or -l localhost. You don’t need to change anything for local-only access.

 

2.3 Modify for Remote Access

  • To allow remote machines to connect to your Memcached server, you need to change the IP address that Memcached listens on.
  • Replace 127.0.0.1 with the server’s public IP address or 0.0.0.0 to listen on all available network interfaces.
-l 192.168.100.20
NOTE:
Allowing Memcached to listen on a public IP or all interfaces can expose your server to potential attacks. Ensure you have proper security measures like firewalls and access control.

 

2.4 Adjust Memory Usage

  • Memcached's default memory allocation is 64MB. You can adjust this based on your server's available memory and requirements.
  • Look for the -m option. For example, to allocate 256MB, change it to:
-m 256

 

2.5 Set Maximum Connections

  • You can specify the maximum number of simultaneous connections Memcached should accept. The default is 1024.
  • Find the -c option and adjust it as needed:
-c 1024

Other Configurations: You can also configure other settings such as verbosity level, socket path for UNIX domain sockets, and more.

How to Install and Configure Memcached on Ubuntu?

 

2.6 Save Changes and Restart Memcached

After making the changes, save and exit the editor. If using nano, press CTRL + O to save and CTRL + X to exit. For the changes to take effect, restart the Memcached service:

sudo systemctl restart memcached

 

2.7 Verify Configuration

You can verify your changes by checking Memcached’s status or using the netstat or ss command to see the listening ports.

 

3. Connecting to Memcached

Connecting to Memcached from different programming languages involves installing specific clients or libraries that facilitate the interaction. Here’s how you can connect to Memcached using PHP and Python:

 

3.1 Using PHP

First, you need to install the php-memcached extension. This extension provides an API for communicating with Memcached servers. You can install it using the following command:

sudo apt install php-memcached

After installation, restart your web server to load the new extension. For Apache, use:

sudo systemctl restart apache2

For Nginx, use:

sudo systemctl restart nginx

Here is a basic example to test the connection to Memcached using PHP:

<?php
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);

$memcached->set('key', 'value');
echo $memcached->get('key');
?>

This code connects to Memcached running on localhost and sets and retrieves a value.

 

3.2 Using Python

For Python, you can use libraries like pymemcache or python-memcached to connect to Memcached. Install the library using pip. For pymemcache:

pip3 install pymemcache

Or, for python-memcached:

pip3 install python-memcached
NOTE:
The pip3 requires python-pip3 to be installed, if you get pip3 command not found then you can install python-pip3 using apt command.

Here's an example of using Python to connect and interact with Memcached:

from pymemcache.client import base

client = base.Client(('127.0.0.1', 11211))
client.set('key', 'value')
print(client.get('key'))

This Python script creates a connection to a Memcached server running on localhost and performs basic set and get operations.

 

4. Securing Memcached

Securing Memcached is crucial, especially when allowing remote access, as unsecured instances can be exploited for malicious purposes, including distributed denial-of-service (DDoS) attacks. Here's how to secure Memcached:

4.1 Bind Memcached to a Local Interface

By default, Memcached binds to localhost (127.0.0.1). Ensure it’s not exposed to the public internet. If remote access is needed, bind it to a private network interface instead of a public one. Edit /etc/memcached.conf and set the -l parameter to your private IP:

-l 192.168.100.20

Replace 192.168.100.20 with the IP address of the server where memcached is running.

4.2 Configuring the Firewall

If remote access is enabled, configure the firewall to allow connections only from specific IPs. For example, using UFW (Uncomplicated Firewall), you can allow a specific IP to connect to the Memcached port (default 11211):

sudo ufw allow from 192.168.100.30 to any port 11211

Replace 192.168.100.30 with the IP address of the client that needs access.

4.3 Disable UDP if Not Required

Memcached's UDP interface can be exploited for reflection DDoS attacks. If not required, it's safer to disable it. In /etc/memcached.conf, add the following option:

-U 0

 

5. Conclusion

Memcached plays a vital role in enhancing application performance through its efficient caching mechanism. By storing frequently accessed data in memory, it significantly reduces database load and improves response times. This is especially crucial for dynamic websites and applications where speed and efficiency are paramount. The ability of Memcached to handle large volumes of data requests makes it an indispensable tool in modern web development, particularly for applications experiencing high traffic. Overall, implementing Memcached can lead to a more responsive user experience, better resource management, and a scalable approach to handling data.

For further information and advanced configurations of Memcached, refer Memcached Official Website for best practices, and latest updates directly from the source.

 

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!