BLOG POSTS
How to Install and Secure Memcached on Ubuntu 24

How to Install and Secure Memcached on Ubuntu 24

Memcached is a high-performance, distributed memory caching system that dramatically speeds up dynamic web applications by reducing database load through RAM-based key-value storage. Installing and properly securing Memcached on Ubuntu 24 is crucial for developers and sysadmins managing high-traffic applications, as it can reduce database queries by up to 90% while serving cached data in microseconds rather than milliseconds. This guide walks you through the complete installation process, essential security hardening steps, and practical configuration examples to get your Memcached instance production-ready.

How Memcached Works Under the Hood

Memcached operates as a distributed hash table stored entirely in RAM, using a simple client-server architecture with a custom binary protocol. When your application requests data, it first checks Memcached using a generated key – if found (cache hit), the data returns instantly; if not (cache miss), your app queries the database and stores the result in Memcached for future requests.

The magic happens through its LRU (Least Recently Used) eviction policy and slab allocation system. Memcached pre-allocates memory in chunks called slabs, each optimized for different data sizes, preventing memory fragmentation. This design makes it incredibly efficient for storing frequently accessed data like database query results, session data, or computed values.

Feature Memcached Redis Database Query
Average Response Time 0.1-1ms 0.1-2ms 10-100ms
Data Persistence None Yes Yes
Memory Usage Very Low Medium High (with connections)
Setup Complexity Simple Medium Complex

Step-by-Step Installation Guide

Let’s get Memcached up and running on your Ubuntu 24 system. The process is straightforward, but we’ll cover both the quick installation and the more robust compilation method.

Method 1: Package Manager Installation

First, update your system and install Memcached from the official Ubuntu repositories:

sudo apt update && sudo apt upgrade -y
sudo apt install memcached libmemcached-tools -y

Verify the installation and check the version:

memcached -h
systemctl status memcached

Method 2: Source Compilation (Recommended for Production)

For better performance and the latest features, compile from source:

# Install build dependencies
sudo apt install build-essential libevent-dev libsasl2-dev -y

# Download and compile latest stable version
cd /tmp
wget http://memcached.org/latest
tar -xzf memcached-*.tar.gz
cd memcached-*
./configure --enable-sasl
make && sudo make install

Basic Configuration

Edit the main configuration file to customize your Memcached instance:

sudo nano /etc/memcached.conf

Here’s a production-ready configuration:

# Memory allocation (in MB)
-m 512

# Listen on localhost only for security
-l 127.0.0.1

# Default port
-p 11211

# Run as memcache user
-u memcache

# Maximum connections
-c 1024

# Verbose logging level
-v

# Enable SASL authentication
-S

Start and enable the service:

sudo systemctl start memcached
sudo systemctl enable memcached

Essential Security Hardening

Out of the box, Memcached is about as secure as leaving your front door wide open. Here’s how to lock it down properly without breaking functionality.

Network Security Configuration

The most critical step is restricting network access. By default, Memcached binds to all interfaces, which is a massive security risk:

# Edit the configuration to bind only to localhost
sudo sed -i 's/^-l.*/-l 127.0.0.1/' /etc/memcached.conf

# Or bind to specific internal IP if needed
echo "-l 192.168.1.100" | sudo tee -a /etc/memcached.conf

Firewall Rules

Configure UFW to block external access while allowing local connections:

sudo ufw deny 11211
sudo ufw allow from 192.168.1.0/24 to any port 11211
sudo ufw reload

SASL Authentication Setup

Enable SASL authentication for an additional security layer:

# Install SASL packages
sudo apt install sasl2-bin libsasl2-modules -y

# Create SASL configuration
sudo mkdir -p /etc/sasl2
sudo tee /etc/sasl2/memcached.conf << EOF
mech_list: plain
log_level: 5
sasldb_path: /etc/sasl2/memcached-sasldb2
EOF

# Create user credentials
sudo saslpasswd2 -a memcached -c -f /etc/sasl2/memcached-sasldb2 cacheuser
sudo chown memcache:memcache /etc/sasl2/memcached-sasldb2

Update your Memcached configuration to enable SASL:

echo "-S" | sudo tee -a /etc/memcached.conf
sudo systemctl restart memcached

System User Security

Ensure Memcached runs with minimal privileges:

# Create dedicated user if not exists
sudo useradd -r -s /bin/false memcache

# Set proper ownership
sudo chown -R memcache:memcache /var/run/memcached

Real-World Configuration Examples

Let's look at practical configurations for different use cases you'll encounter in production environments.

Web Application Caching

For a typical LAMP stack serving a WordPress or Laravel application:

# /etc/memcached.conf
-m 1024                    # 1GB RAM allocation
-l 127.0.0.1              # Local access only
-p 11211                  # Standard port
-u memcache               # Security user
-c 2048                   # Handle more connections
-t 4                      # Use 4 threads
-R 200                    # Limit requests per event
-C                        # Disable CAS operations for speed

Multi-Server Distribution

For distributed caching across multiple servers:

# Server 1 configuration
-m 2048
-l 192.168.1.10
-p 11211

# Server 2 configuration  
-m 2048
-l 192.168.1.11
-p 11211

# Client-side consistent hashing handles distribution

High-Traffic API Caching

Configuration optimized for API response caching:

# /etc/memcached.conf
-m 4096                   # 4GB for large dataset
-l 127.0.0.1
-p 11211
-u memcache
-c 4096                   # High connection limit
-t 8                      # More threads for CPU-bound operations
-I 5m                     # 5MB max item size for large JSON responses
-f 1.25                   # Growth factor tuning

Testing and Validation

Let's verify everything works correctly with some practical tests:

# Basic connectivity test
echo "stats" | nc 127.0.0.1 11211

# Store and retrieve test data
printf "set test_key 0 3600 5\r\nhello\r\n" | nc 127.0.0.1 11211
printf "get test_key\r\n" | nc 127.0.0.1 11211

# Using memcached tools
echo "hello world" | memcflush --servers=localhost
memcstat --servers=localhost

Performance Benchmarking

Test your Memcached performance with realistic workloads:

# Install memcache client for testing
sudo apt install php-memcached -y

# Simple PHP benchmark script
cat << 'EOF' > memcache_benchmark.php
addServer('127.0.0.1', 11211);

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $memcached->set("key_$i", "value_$i", 3600);
}
$write_time = microtime(true) - $start;

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $memcached->get("key_$i");
}
$read_time = microtime(true) - $start;

echo "Write time: " . round($write_time, 4) . "s\n";
echo "Read time: " . round($read_time, 4) . "s\n";
EOF

php memcache_benchmark.php

Common Issues and Troubleshooting

Here are the most frequent problems you'll encounter and their solutions:

Connection Refused Errors

  • Check if Memcached is running: systemctl status memcached
  • Verify binding configuration: netstat -tulpn | grep 11211
  • Review firewall rules: sudo ufw status
  • Check logs: journalctl -u memcached -f

Memory-Related Issues

Monitor memory usage and evictions:

# Check current memory usage
memcstat --servers=localhost | grep -E "(bytes|evictions|cmd_get|cmd_set)"

# Monitor evictions in real-time
watch "echo 'stats' | nc 127.0.0.1 11211 | grep evictions"

Performance Degradation

Common causes and fixes:

  • High eviction rate: Increase memory allocation
  • Connection limits reached: Adjust -c parameter
  • Thread contention: Tune -t based on CPU cores
  • Network latency: Use local connections only

SASL Authentication Problems

# Test SASL authentication
memcstat --servers=localhost --username=cacheuser --password=yourpassword

# Debug SASL issues
sudo journalctl -u memcached | grep -i sasl

Best Practices and Optimization

After managing Memcached in production for years, here are the practices that actually matter:

Memory Management

  • Allocate 75% of available RAM to avoid swapping
  • Monitor slab statistics to optimize chunk sizes
  • Set appropriate expiration times to prevent memory bloat
  • Use consistent key naming conventions

Key Design Patterns

# Good key patterns
user:123:profile
article:456:content
api:v1:endpoint:/users/123

# Bad key patterns (spaces, special chars)
"user data for john"
user-123-profile!

Monitoring and Alerting

Set up basic monitoring with this script:

#!/bin/bash
# memcached-monitor.sh
STATS=$(echo "stats" | nc 127.0.0.1 11211)
EVICTIONS=$(echo "$STATS" | grep "evictions" | awk '{print $3}')
HIT_RATE=$(echo "$STATS" | grep -E "(cmd_get|get_hits)" | awk 'NR==1{gets=$3} NR==2{hits=$3} END{if(gets>0) print (hits/gets)*100}')

echo "Hit Rate: ${HIT_RATE}%"
echo "Evictions: $EVICTIONS"

# Alert if hit rate drops below 80%
if (( $(echo "$HIT_RATE < 80" | bc -l) )); then
    echo "WARNING: Low hit rate detected!"
fi

Integration Examples

Here's how to integrate Memcached with popular programming languages and frameworks:

PHP Integration

memcached = new Memcached();
        $this->memcached->addServer('127.0.0.1', 11211);
        
        // SASL authentication if enabled
        $this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
        $this->memcached->setSaslAuthData('cacheuser', 'password');
    }
    
    public function get($key) {
        return $this->memcached->get($key);
    }
    
    public function set($key, $value, $expiration = 3600) {
        return $this->memcached->set($key, $value, $expiration);
    }
}
?>

Python Integration

import pymemcache
from pymemcache.client.base import Client

class MemcacheManager:
    def __init__(self):
        self.client = Client(('127.0.0.1', 11211))
    
    def get(self, key):
        return self.client.get(key)
    
    def set(self, key, value, expire=3600):
        return self.client.set(key, value, expire=expire)
    
    def delete(self, key):
        return self.client.delete(key)

For comprehensive documentation and advanced configuration options, check the official Memcached wiki and project documentation.

Memcached transforms application performance when properly configured and secured. Start with the basic installation, implement security measures immediately, and gradually optimize based on your specific use case and monitoring data. The investment in proper setup pays dividends in reduced server load and improved user experience.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked