How to Install Memcached on Ubuntu Linux

Memcached is a high-performance, distributed in-memory cache that speeds up dynamic applications by reducing database load. Consequently, it stores frequently accessed data in RAM for fast retrieval, making it a staple for web apps that need low latency and horizontal scalability.

Meanwhile, on Ubuntu you can install Memcached from the default repositories for a stable, unattended setup or compile the latest release from source when you need newer features or custom build options. The sections below cover both methods along with service management, configuration, security, and language integrations.

Choose Your Memcached Installation Method

Generally, most users should install Memcached from Ubuntu’s repositories for reliability and automatic updates. This path relies on APT (Advanced Package Tool), Ubuntu’s package manager that plays a role similar to combining Windows Update with the Microsoft Store on Windows, so dependencies and security patches arrive automatically. Alternatively, compile from source when you require the newest upstream release or specific build flags (for example, SASL support).

MethodVersion/ChannelStabilityBest For
APT (Ubuntu Repositories)Distro-packagedHigh (automatic security and bug fixes)Default choice for servers and workstations
Compile from SourceLatest upstreamVaries (manual updates, more control)Needing newest features, custom build options

Method 1: Install Memcached via APT

Update Package Index

First, update your package lists and process any pending upgrades before installing Memcached.

sudo apt update

Then upgrade any outdated packages:

sudo apt upgrade

Install Memcached from Ubuntu Repositories

Next, remember that Ubuntu’s repositories include Memcached. This version meets the needs of most deployments and is the recommended default.

Afterward, install Memcached and optional tools:

sudo apt install memcached libmemcached-tools

Verify Memcached Installation

Finally, confirm the installation by checking the version:

memcached -V

This confirms Memcached is ready to use on your system.

Method 2: Install Memcached from Source

Alternatively, compile from source when you need the latest upstream features or custom build options. This is common for testing, enabling optional features, or aligning with a specific build toolchain.

Fetch the Memcached Source

First, download the latest release archive directly:

wget https://memcached.org/latest

If you are new to wget and want to explore more download patterns, refer to the wget command examples guide.

Unpack the Memcached Source Archive

Next, extract the gzip archive (the download is compressed even when the filename appears as latest):

tar -xvzf latest

Replace the filename if your download uses a specific version string (for example, memcached-1.6.x.tar.gz).

Install Build Dependencies

Then install essential build tools and libraries:

sudo apt install build-essential libevent-dev libc6-dev

Additionally, add SASL support (authentication) by installing the headers and enabling the feature at configure time:

sudo apt install libsasl2-dev

Configure the Build

First, navigate to the extracted source directory:

cd memcached-x.x.x

Then configure with a standard prefix. Add --enable-sasl if you installed SASL headers:

# Without SASL authentication
./configure --prefix=/usr/local

# With SASL authentication (requires libsasl2-dev)
# ./configure --prefix=/usr/local --enable-sasl

Compile the Memcached Source Code

After configuration completes, compile the source:

make

Afterward, you can check the binary version from the build directory if desired:

./memcached -V

Install the Compiled Binaries

Next, install Memcached system-wide:

sudo make install

Verify Installation (Source Method)

Finally, confirm the installed version:

memcached -V

This returns the installed version and confirms a successful installation.

Set Up a systemd Service (Source Install)

To wrap up the source install method, create a systemd unit so you can manage Memcached with systemctl. APT installs include a unit by default; skip this if you used APT.

Creating a Dedicated User and Group

First, create a dedicated, non-login account before starting the service:

sudo useradd -r -s /usr/sbin/nologin -U -M memcache

As a result, this creates a system user and group without a login shell.

Creating the Service File

Next, create the unit file with administrative privileges (using nano in this example):

sudo nano /etc/systemd/system/memcached.service

Then paste the following minimal, production-friendly configuration and adjust flags (-m, -c, -t, etc.) to suit your host:

[Unit]
Description=Memcached In-Memory Object Cache
After=network.target

[Service]
Type=simple
User=memcache
Group=memcache
ExecStart=/usr/local/bin/memcached -u memcache -m 64 -p 11211 -l 127.0.0.1 -c 1024 -t 4 -o modern
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target

Consequently, this configuration ensures the Memcached service starts after the network is online.

Saving and Closing the Text Editor

After editing, save and exit (in nano: CTRL+X, then Y, then Enter).

Reloading the Systemd Configuration

Finally, reload units and enable the service to start immediately and on boot:

sudo systemctl daemon-reload
sudo systemctl enable memcached --now

Memcached Service Commands

Overall, 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

By default, Memcached starts automatically after installation (APT) or after enabling the systemd unit (source). To confirm its status, run:

systemctl status memcached

Typically, a healthy service shows an active (running) state similar to:

● memcached.service - Memcached In-Memory Object Cache
      Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled)
      Active: active (running) since Tue 2025-11-11 10:15:42 UTC; 5min ago
    Main PID: 1234 (memcached)
        Tasks: 10 (limit: 4567)
      Memory: 12.3M
          CPU: 150ms
      CGroup: /system.slice/memcached.service
                 └─1234 /usr/bin/memcached -m 64 -p 11211 -l 127.0.0.1 -c 1024

Otherwise, if it is not active, start it and enable it at boot with:

sudo systemctl enable memcached --now

Additional Memcached Service Commands

Additionally, familiarizing yourself with various service commands is vital for efficient Memcached management. Below are some of the key commands:

To start Memcached within the current user session:

sudo systemctl start memcached

Next, set Memcached to automatically start at system boot:

sudo systemctl enable memcached

To stop the Memcached service:

sudo systemctl stop memcached

Likewise, prevent Memcached from starting automatically at system boot:

sudo systemctl disable memcached

Finally, restart Memcached when you need to apply changes:

sudo systemctl restart memcached

These commands provide a solid foundation for managing the Memcached service and ensuring it’s running according to your preferences.

Confirm the Listening Port

Verify that Memcached is listening on the loopback interface at port 11211:

sudo ss -tlnp | grep ":11211"

The sudo prefix is required because the -p flag only exposes process details to root.

Example output for a local Memcached listener:

LISTEN 0      1024         127.0.0.1:11211       0.0.0.0:*    users:(("memcached",pid=1234,fd=26))

This shows processes with a TCP listener on port 11211 so you can confirm Memcached is ready to accept connections.

Configure Memcached

Configuration differs slightly depending on how you installed Memcached. The APT package uses a Debian-style config file at /etc/memcached.conf that is parsed by the service unit. For source installs, pass flags directly in the systemd unit’s ExecStart line.

Exposing Memcached directly to the internet is rarely necessary and increases the risk of abuse. Keep it bound to 127.0.0.1 whenever possible, and if you must allow remote access, restrict it to trusted networks and protect it with a firewall.

APT Install: Edit /etc/memcached.conf

To begin, open the configuration file with your editor of choice (example uses nano):

Specifically, you can do this by running the command:

sudo nano /etc/memcached.conf

Afterward, review the minimal example below and adjust values for your host. Avoid using daemon flags here; systemd manages the process lifecycle.

# Example /etc/memcached.conf (APT install)

# Memory in MB
-m 64

# TCP port
-p 11211

# Bind address (loopback by default)
-l 127.0.0.1

# Maximum simultaneous connections
-c 1024

# Optional: disable UDP
-U 0

# Verbosity (use sparingly in production)
-v

Listening Address

By default, Memcached binds to 127.0.0.1. Adjust the -l parameter only if you need remote access and protect it with a firewall or private network.

Disable UDP (Optional)

Otherwise, if you do not require UDP, disable it to reduce attack surface.

Adjust Memory Allocation

Similarly, increase -m for larger datasets. For example, to allocate 2 GB of memory, set -m 2000. Ensure the host has enough free RAM.

Additionally, ensure this setting is adjusted according to your server’s available memory and requirements.

Apply Configuration Changes

After editing the configuration, restart Memcached to apply the updates:

sudo systemctl restart memcached

Additional Configuration Tips

Beyond the basic settings, there are a variety of additional parameters you can configure to fine-tune Memcached to suit your needs better.

To continue, here are some examples and brief explanations:

These tuning flags become part of Memcached’s runtime invocation, so add them inside /etc/memcached.conf for APT installs or append them to the ExecStart line in your custom systemd unit for source builds, then restart the service to pick up the change.

Specify User and Group

First, run Memcached under a dedicated user with -u. For example, to run as memcache:

-u memcache

Enable Large Memory Pages

Additionally, huge pages can improve performance on some workloads. Enable with -L if supported (requires appropriate kernel settings):

-L

Configure Maximum Item Size

By default, the maximum item size is 1 MB. However, increase with -I when you need more headroom. For a 5 MB item size:

-I 5m

Set the Maximum Number of Threads

Likewise, Memcached defaults to four threads. Adjust to match CPU cores and workload. To use eight threads:

-t 8

Adjust Idle Timeout

Furthermore, adjust idle connection timeouts with advanced options (-o):

-o idle_timeout=600

Enable SASL Authentication

To require authentication, enable SASL support with -S. Note: this requires building Memcached with --enable-sasl and installing the SASL libraries:

-S

Then restart Memcached after configuration changes:

sudo systemctl restart memcached

Secure Memcached with UFW

Memcached binds to the loopback interface by default. If you expose it to a network (for clustering or remote clients), restrict access with a firewall. The examples below use UFW (Uncomplicated Firewall). For a broader overview of UFW on Ubuntu, see the guide to installing and configuring UFW firewall on Ubuntu.

Check UFW Availability

First, check if UFW is installed:

sudo ufw --version

If UFW is not installed, add it before creating rules.

Install UFW (if needed)

Next, install UFW:

sudo apt install ufw

Keep UFW disabled until your allow rules are defined, especially on headless VPS or cloud servers.

Allow SSH or Console Access Before Enabling

Before enabling anything, always permit your management channel (typically SSH on port 22/tcp or the OpenSSH application profile) so you do not lose access:

sudo ufw allow OpenSSH

Enable UFW only after your SSH or console rule is in place. Enabling the firewall without a management rule can immediately disconnect remote sessions.

Create UFW Rules for Memcached

Afterward, allow only trusted sources. Examples below show a single trusted IP and a subnet for internal clusters.

Single IP Network Connection

For a single trusted IP:

sudo ufw allow proto tcp from <ip_address> to any port 11211

Replace <ip_address> with the client’s IP.

Cluster Network with Multiple Instances

For a trusted subnet (for internal clusters):

sudo ufw allow proto tcp from <subnet> to any port 11211

Replace <subnet> with your CIDR block (for example, 10.0.0.0/24).

Enable UFW After Adding Rules

With your SSH and Memcached rules ready, enable the firewall. Confirm you have console access in case you need to revert changes:

sudo ufw enable

If UFW was already active, run sudo ufw reload after updating rules.

Confirm UFW Configuration

Finally, list active rules:

sudo ufw status

Verify the rules match your intentions and security policy. A simple example with a single Memcached rule might look like:

Status: active

To                         Action      From
--                         ------      ----
11211/tcp                  ALLOW       10.0.0.0/24

For broader firewall management on Ubuntu (including enabling or disabling the firewall entirely), refer to the Ubuntu firewall management guide.

Install Memcached Language Libraries

Memcached integrates with common languages through client libraries. Accordingly, the sections below show package installs for PHP, Python, and Perl, plus brief web server notes.

PHP: Install and Enable Memcached

Apache HTTP Server

First, install PHP and the Memcached extension for Apache:

sudo apt install php php-cli libapache2-mod-php php-memcached

This installs PHP, Apache’s PHP module, and the Memcached extension. If you are still setting up PHP itself, the PHP on Ubuntu installation guide covers additional module and version options.

Enable Extension and Restart Apache

Next, enable the extension and restart Apache:

sudo phpenmod memcached && sudo systemctl restart apache2

This activates the Memcached extension and restarts Apache to apply changes.

Nginx with PHP-FPM

Alternatively, for Nginx install PHP-FPM and the Memcached extension, then configure your server block. Replace the PHP-FPM socket path to match your installed version (for example, /run/php/php8.3-fpm.sock):

sudo apt install php php-cli php-fpm php-memcached
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:/run/php/php-fpm.sock; # adjust to your PHP-FPM socket path
    }

    location ~ /\.ht {
        deny all;
    }
}

As a result, this sets up PHP-FPM with Nginx, and the Memcached PHP extension allows your app to connect to the Memcached service.

Other Languages

Python

For Python, install a client library:

sudo apt install python3-pymemcache

This installs a modern client for interacting with Memcached from Python.

Perl

Likewise, install a Perl client library:

sudo apt install libcache-memcached-libmemcached-perl

Access Memcached from the Command Line

Additionally, you can query Memcached directly for quick checks and diagnostics using Telnet or nc (netcat).

Connect to Memcached

To start, connect to the local Memcached instance with Telnet:

telnet localhost 11211

On success, you will see output like:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

If Telnet is not installed, install it quickly:

sudo apt install telnet

For a deeper look at Telnet installation and usage on Ubuntu, see the dedicated guide.

Send Memcached commands with netcat

Netcat (the nc command) can talk to Memcached the same way but without an interactive prompt, which makes it ideal for scripts or automation.

First, install the OpenBSD flavor of netcat if it is not already present:

sudo apt install netcat-openbsd

Then pipe a simple command sequence into nc to request statistics and exit cleanly:

printf 'stats\r\nquit\r\n' | nc localhost 11211

The response mirrors the Telnet output with each statistic on its own line, and the command terminates automatically because of the trailing quit.

Retrieve Memcached Statistics

After connecting, immediately run stats for a summary:

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.

Analyze Memory Partitions

Next, inspect slabs (memory partitions):

stats slabs

Then list slab items:

stats items

Manage Cached Data

Afterward, use stats cachedump to list keys in a given slab. For example, list all items in slab 1:

stats cachedump [slab ID] [number of items, 0 for all items]

Example:

stats cachedump 1 0

Expected output:

ITEM testkey [9 b; 1296857316 s]
END

Next, fetch the value for a key with get:

get testkey

Expected output:

VALUE testkey 0 9
test data
END

Delete Cached Items

Finally, delete a cached key (example testkey):

delete testkey

Confirmation:

DELETED

Troubleshooting

  • Service fails to start: Check logs with journalctl -u memcached -e. Ensure no conflicting flags (avoid -d when using systemd).
  • Port already in use: Verify listeners with sudo ss -tlnp | grep ":11211" and adjust the -p port if required.
  • Permission errors: Confirm the memcache user exists and owns any Unix sockets you configure.
  • SASL not working: Rebuild with --enable-sasl, install libsasl2-dev, and pass -S at runtime.
  • Remote access blocked: Ensure -l is set appropriately and UFW (or another firewall) allows trusted sources only.

Uninstall Memcached

APT Install

For package installs, remove the service and packages with:

sudo systemctl disable memcached --now
sudo apt purge memcached libmemcached-tools

Source Install

Alternatively, if you installed from source, remove the unit and binary (paths may vary if you changed --prefix):

sudo systemctl disable memcached --now
sudo rm -f /etc/systemd/system/memcached.service
sudo systemctl daemon-reload
sudo rm -f /usr/local/bin/memcached

Conclusion

Memcached provides fast, in-memory caching to cut database load and latency. You now have two reliable install paths (APT or source), a proper systemd setup, safe defaults for configuration and security, and language integrations to use it in your applications.

Leave a Comment