Website Vidya
Linux & ServersStep-by-Step Guide

How to Install and Configure Memcached on Ubuntu 24.04

Learn how to install and configure memcached on ubuntu 24.04 with memory tuning, local loopback security, PHP/Python integration, and firewall rules.

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Install and Configure Memcached on Ubuntu 24.04
AI Executive SummaryWebsiteVidya AI

5 min read

Learn how to install and configure memcached on ubuntu 24.04 with memory tuning, local loopback security, PHP/Python integration, and firewall rules.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Installing Memcached and Client Utilities
  • Step 2: Hardening and Tuning Configuration (/etc/memcached.conf)
Grounded in full engineering runbookWebsiteVidya AI Engine

Dynamic web applications and database-driven APIs often face severe input/output bottlenecks when querying relational databases repeatedly for identical data.

Memcached is an open-source, high-performance, distributed in-memory key-value caching daemon designed to alleviate database load by storing arbitrary chunks of data (strings, objects, API responses) directly in RAM.

By serving cached queries directly from volatile memory in sub-millisecond response times, Memcached dramatically accelerates website loading times and reduces database server CPU utilization.

Configuring Memcached properly on Ubuntu 24.04 LTS requires tuning memory allocations and enforcing strict network interface binding to prevent public exposure.

Advertisement

In this guide, we walk through how to install and configure memcached on ubuntu 24.04, secure its network configuration, and connect client applications.

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

Advertisement
  • A server running Ubuntu 24.04 LTS or Ubuntu 22.04 LTS.
  • A non-root user account with sudo administrative privileges.
  • UFW firewall installed and active.
  • An application stack (such as PHP, Python, or Node.js) that utilizes caching.

Step 1: Installing Memcached and Client Utilities

Ubuntu 24.04 includes the latest stable release of Memcached natively in the standard package archives.

Install memcached along with libmemcached-tools (which provides diagnostic CLI utilities like memcstat):

Verify that the systemd service starts automatically:

# Update package index:
sudo apt update

# Install Memcached and management utilities:
sudo apt install -y memcached libmemcached-tools

# Check service status:
sudo systemctl status memcached
# Expected output confirms:
# Active: active (running) since ...

# Ensure service is enabled to start on system boot:
sudo systemctl enable memcached

Step 2: Hardening and Tuning Configuration (/etc/memcached.conf)

The primary configuration file for Memcached is located at /etc/memcached.conf.

Advertisement

By default, Memcached allocates 64 MB of RAM and listens on loopback address 127.0.0.1 on port 11211.

For production workloads, tune the allocated memory limit and verify that public listening interfaces are strictly disabled:

Open the configuration file in a text editor:

# Open configuration file:
sudo nano /etc/memcached.conf

# 1. Set Memory Cap (e.g., 512 MB or 1024 MB):
# -m 1024

# 2. Enforce listening strictly on localhost loopback:
# -l 127.0.0.1

# 3. Specify listening TCP port:
# -p 11211

# 4. Disable UDP to protect against DDoS amplification attacks:
# -U 0

# Save and exit (Ctrl+O, Enter, Ctrl+X in nano).

# Restart Memcached to apply parameters:
sudo systemctl restart memcached

Disabling UDP to Prevent DDoS Amplification

Historically, misconfigured Memcached servers exposed over UDP on the public internet were exploited to launch record-breaking Distributed Denial of Service (DDoS) reflection attacks.

Enforcing -U 0 completely disables UDP socket listeners, guaranteeing that Memcached only communicates over reliable, TCP-handshaked connections.

Step 3: Verifying Socket Binding and Memory Statistics

Confirm that Memcached is listening exclusively on the internal loopback adapter and that UDP is closed:

Use the ss network diagnostic utility to inspect listening sockets:

Query active cache statistics using memcstat:

# Verify TCP socket is bound to 127.0.0.1:11211:
sudo ss -tulpn | grep memcached
# Output confirms:
# tcp  LISTEN 0  1024  127.0.0.1:11211  0.0.0.0:*  users:(("memcached",pid=1234,fd=26))

# Query live cache metrics:
memcstat --servers="127.0.0.1:11211"
# Output snippet:
# Server: 127.0.0.1 (11211)
#   pid: 1234
#   uptime: 120
#   time: 1718000000
#   version: 1.6.24
#   limit_maxbytes: 1073741824 (1024 MB)
#   curr_items: 0
#   total_items: 0

Step 4: Integrating Memcached with PHP and Python Applications

To utilize Memcached in web applications, install the corresponding client driver library for your programming language.

For PHP applications (such as WordPress, Laravel, or Symfony), install the php-memcached module:

For Python applications (such as Django or Flask), install pymemcache via pip:

# Install PHP Memcached extension and restart web server:
sudo apt install -y php-memcached
sudo systemctl restart php8.3-fpm # or sudo systemctl restart apache2

# Verify PHP extension:
php -m | grep memcached
# Output: memcached

# Test caching with Python in a virtual environment:
python3 -m pip install pymemcache
python3 -c '
from pymemcache.client.base import Client
client = Client(("127.0.0.1", 11211))
client.set("site_name", "Website Vidya")
print("Cached Value:", client.get("site_name").decode("utf-8"))
'
# Output: Cached Value: Website Vidya

Step 5: Configuring Firewall Rules for Remote Cluster Access

If Memcached operates on a dedicated caching server accessed by separate application servers over a private network, bind Memcached to the server's private IP (e.g. 192.168.1.100).

Never expose port 11211 to the public internet.

Restrict access in UFW strictly to the trusted IP address of the application server:

# Allow incoming Memcached connections ONLY from the application server:
sudo ufw allow from 192.168.1.50 to any port 11211 proto tcp comment 'Memcached from App Server'

# Verify active UFW rules:
sudo ufw status

Step 6: Monitoring Cache Hit Ratios and Health Metrics

To ensure Memcached operates efficiently, monitor cache hit ratios and memory utilization regularly.

A high cache miss ratio indicates that the allocated memory cap is too small, or that cache keys are expiring too rapidly.

You can query Memcached telemetry directly via netcat (nc) or telnet over localhost:

# Query full stats directly via netcat:
echo "stats" | nc 127.0.0.1 11211

# Calculate cache hit ratio from output metrics:
# get_hits / (get_hits + get_misses) * 100

# Flush all stored cache items immediately (use with caution):
echo "flush_all" | nc 127.0.0.1 11211
# Output: OK

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

memcached: connection refused when testing from application

Cause: Memcached service is stopped or bound to a different IP address than the client target.

Resolution: Check sudo systemctl status memcached and ensure -l in /etc/memcached.conf matches your application's connection string.

sudo ss -tulpn | grep 11211

Cache evictions occurring frequently despite available system RAM

Cause: The allocated memory cap (-m) in /etc/memcached.conf is too low for the dataset size.

Resolution: Increase the -m parameter (e.g. from 64 to 1024) and restart Memcached.

sudo sed -i 's/^-m .*/-m 1024/' /etc/memcached.conf && sudo systemctl restart memcached

PHP Class 'Memcached' not found

Cause: The php-memcached package is not installed or PHP-FPM / Apache was not reloaded.

Resolution: Install php-memcached and restart the PHP-FPM daemon: sudo systemctl restart php8.3-fpm.

sudo apt install -y php-memcached && sudo systemctl restart php*-fpm

Security Best Practices and Hardening

Never bind Memcached to 0.0.0.0 or a public IP address without SASL authentication and strict firewall filters.

Always set -U 0 in /etc/memcached.conf to eliminate UDP amplification attack vectors.

If remote caching is required across untrusted networks, encapsulate traffic inside a WireGuard VPN tunnel.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Memcached is a multithreaded, simple key-value cache designed purely for fast volatile memory storage. Redis is single-threaded, supports rich data structures (lists, sets, hashes), provides disk persistence, and includes pub/sub messaging.
No. Memcached is strictly an in-memory caching system. If the service restarts or the server reboots, all cached items are cleared immediately.
Memcached uses an LRU (Least Recently Used) eviction algorithm. When the configured memory limit is reached, it automatically discards the oldest, least accessed items to allocate space for new keys.
Yes. Memcached supports SASL (Simple Authentication and Security Layer) authentication when compiled with SASL support and started with the -S flag.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout