How to Install and Configure Memcached on an Ubuntu VPS Print

  • configure Memcached Ubuntu, Memcached Ubuntu 26.04, KVM VPS, WordPress Memcached, Memcached, install Memcached Ubuntu, Memcached PHP, Memcached memory limit, Memcached localhost, Memcached Ubuntu 24.04, WordPress object cache, Memcached security, WooCommerce caching, Memcached monitoring, Memcached vs Redis, VPS hosting, Memcached caching, Owned Networks, Linux VPS optimization, Memcached VPS, PHP Memcached extension
  • 0

How to Install and Configure Memcached on an Ubuntu VPS

Memcached is an open-source, high-performance, distributed memory caching system designed to accelerate websites and applications by storing frequently accessed data in RAM.

Instead of repeatedly querying a database or recalculating expensive application results, applications can retrieve previously cached information from Memcached.

This can reduce database load, improve response times, and help websites handle higher traffic volumes.

Memcached is commonly used with PHP applications, WordPress, WooCommerce, and database-backed websites.

In this tutorial, you will learn how to install and configure Memcached on an Ubuntu VPS, secure its network access, allocate memory, integrate it with PHP, configure WordPress object caching, monitor performance, and troubleshoot common problems.

The instructions apply to Ubuntu 24.04 LTS, Ubuntu 26.04 LTS, and other supported Ubuntu releases.

Prerequisites

  • An Ubuntu VPS with root or sudo access.
  • SSH access to the server.
  • At least 1 GB of RAM for basic testing; production requirements depend on your workload.
  • Basic familiarity with Linux commands.
  • Optional: An existing PHP or WordPress installation.

Need a Linux server for your applications? Explore Owned Networks KVM VPS hosting for full root access and flexible server resources.

1. What Is Memcached?

Memcached is a memory-based key-value caching system.

Applications store temporary information using a unique key. When the information is needed again, the application can retrieve it directly from memory.

A simplified caching workflow looks like this:

Application Request
        |
        v
Check Memcached
        |
        +-- Cache Hit --> Return Cached Data
        |
        +-- Cache Miss
                |
                v
          Query Database
                |
                v
          Store in Cache
                |
                v
          Return Result

Memcached is particularly useful when applications repeatedly request information that changes infrequently.

Common use cases include:

  • Database query result caching.
  • WordPress object caching.
  • Temporary application data.
  • Frequently accessed configuration data.
  • Expensive computational results.
  • Application-level caching.

Important: Memcached is designed for temporary data. Cached information can disappear when the service restarts, memory becomes constrained, or keys expire.

Applications should remain functional when cached data is unavailable.

2. Memcached vs. Redis

Memcached and Redis are both widely used for in-memory caching, but they have different capabilities.

Feature Memcached Redis
Primary purpose Simple distributed caching Caching and general-purpose data storage
Data model Key-value cache Multiple data structures
Persistence No built-in persistence Supports persistence
Memory eviction Automatic cache eviction Configurable eviction policies
Queues and streams Not a primary feature Supported
PHP integration Supported Supported
WordPress object caching Supported through compatible integrations Supported through compatible integrations

Choose Memcached when you need a straightforward caching layer for temporary data.

Choose Redis when your application requires additional data structures, persistence, or other Redis-specific capabilities.

For Redis installation instructions, see our Redis configuration tutorial.

3. Update Ubuntu Package Repositories

Before installing Memcached, update the package index:

sudo apt update

Review available upgrades:

apt list --upgradable

On production servers, apply operating system upgrades during an appropriate maintenance window.

4. Install Memcached on Ubuntu

Install Memcached using Ubuntu's package manager:

sudo apt install -y memcached

Verify the installed version:

memcached -h | head -n 5

Check the service status:

sudo systemctl status memcached --no-pager

If Memcached is not running, start it:

sudo systemctl start memcached

Enable Memcached at system startup:

sudo systemctl enable memcached

Memcached should now be installed and running.

5. Locate the Memcached Configuration File

On Ubuntu package installations, the Memcached configuration file is commonly located at:

/etc/memcached.conf

Before making changes, create a timestamped backup:

sudo cp -a /etc/memcached.conf \
"/etc/memcached.conf.backup.$(date +%Y%m%d-%H%M%S)"

Verify the backup:

sudo ls -lh /etc/memcached.conf.backup.*

Open the configuration:

sudo nano /etc/memcached.conf

Configuration options typically appear as command-line arguments, one per line.

After making changes, restart Memcached:

sudo systemctl restart memcached

Important: Restarting Memcached clears its in-memory cache. Applications may temporarily generate additional database queries while rebuilding cached data.

6. Secure Memcached Network Access

Memcached should not be directly accessible from the public internet.

For applications running on the same VPS, bind Memcached to localhost.

Edit the configuration:

sudo nano /etc/memcached.conf

Locate the listening address option:

-l 127.0.0.1

Ensure Memcached listens only on the loopback interface.

Memcached commonly uses TCP port 11211.

Verify the configured port:

-p 11211

Disable UDP support:

-U 0

UDP should remain disabled unless your application specifically requires it and the associated security risks have been evaluated.

Restart Memcached:

sudo systemctl restart memcached

Verify the listening address:

sudo ss -tlnp | grep 11211

Expected listening address:

127.0.0.1:11211

Security warning: Never expose Memcached port 11211 directly to the public internet. Misconfigured Memcached servers have historically been abused for reflection and amplification attacks.

7. Configure Memcached Memory Allocation

Memcached stores cached data in RAM.

The amount of memory allocated to Memcached should reflect the available VPS resources and application requirements.

Open the configuration:

sudo nano /etc/memcached.conf

Locate the memory option:

-m 64

This example allocates approximately 64 MB for cached items.

To allocate 256 MB:

-m 256

To allocate 512 MB:

-m 512

For a VPS with 4 GB of RAM, 256 MB or 512 MB may be a reasonable starting point for some caching workloads.

However, the correct allocation depends on:

  • Available VPS RAM.
  • Database memory requirements.
  • PHP-FPM worker consumption.
  • Web server memory usage.
  • Application cache size.
  • Expected traffic volume.

Important: The -m setting controls memory available for item storage. Total Memcached process memory consumption can be higher because of internal overhead and other allocations.

Leave sufficient memory for the operating system and other services.

8. Configure the Maximum Number of Connections

Memcached supports a configurable maximum number of simultaneous connections.

In the configuration file, locate:

-c 1024

This example allows up to 1,024 simultaneous connections.

For applications requiring additional connections, the limit can be increased after evaluating available resources and file descriptor limits.

For example:

-c 2048

Recommendation: Do not increase connection limits without evidence of connection exhaustion. Excessive connection counts can increase memory and operating system resource consumption.

9. Configure Memcached Worker Threads

Memcached uses worker threads to process client requests.

The thread count can be configured using:

-t 4

This example configures four worker threads.

For smaller VPS environments, the default thread configuration is often sufficient.

Increasing the thread count does not automatically improve performance.

Evaluate CPU availability, workload concurrency, and actual request throughput before changing this setting.

10. Restart and Verify Memcached

After updating the configuration, restart the service:

sudo systemctl restart memcached

Verify that the service started successfully:

sudo systemctl status memcached --no-pager

Check the listening socket:

sudo ss -tlnp | grep 11211

Review recent service logs:

sudo journalctl -u memcached -n 100 --no-pager

If Memcached fails to start, review the configuration file for unsupported options, invalid values, or duplicate settings.

11. Install Memcached Tools

Ubuntu provides utilities for inspecting Memcached statistics.

Install the tools package:

sudo apt install -y libmemcached-tools

Verify that Memcached is responding:

memcstat --servers=127.0.0.1:11211

The command should display server statistics when the connection succeeds.

If your installation uses authentication or a different network configuration, additional client options may be required.

12. Check Memcached Statistics

Memcached provides statistics that help administrators evaluate cache performance.

Use:

memcstat --servers=127.0.0.1:11211

Important metrics include:

  • curr_items — Number of items currently stored.
  • total_items — Total number of items stored since startup.
  • bytes — Memory occupied by cached items.
  • limit_maxbytes — Configured item storage limit.
  • get_hits — Successful cache retrievals.
  • get_misses — Cache retrievals where the key was unavailable.
  • evictions — Items removed to make room for new data.
  • curr_connections — Current client connections.

These metrics help identify whether Memcached is providing useful cache hits and whether the configured memory allocation is sufficient.

13. Understand Memcached Cache Hit Ratio

The cache hit ratio indicates how often applications successfully retrieve requested items from Memcached.

A basic calculation is:

Cache Hit Ratio =
get_hits / (get_hits + get_misses) * 100

For example:

get_hits   = 9000
get_misses = 1000

Cache Hit Ratio = 90%

A higher hit ratio often indicates that the cache is serving frequently requested information effectively.

However, there is no universal ideal cache hit ratio.

Interpret the metric alongside application behavior, cache expiration policies, workload patterns, and database performance.

14. Understand Cache Evictions

Memcached automatically removes cached items when necessary to accommodate new data.

This behavior is expected for a temporary caching system.

Check the evictions metric using:

memcstat --servers=127.0.0.1:11211

A growing eviction count may indicate that the application is storing more data than the allocated cache can retain.

However, evictions are not automatically a problem.

Investigate whether eviction activity coincides with:

  • Lower cache hit ratios.
  • Higher database query volumes.
  • Increased application response times.
  • Unexpected memory pressure.

If necessary, adjust cache expiration behavior, optimize stored objects, or increase the memory allocation.

15. Install the Memcached PHP Extension

PHP applications require a compatible client extension to communicate with Memcached.

Install the PHP Memcached extension:

sudo apt install -y php-memcached

Verify that PHP recognizes the extension:

php -m | grep -i memcached

Expected output:

memcached

Check the installed PHP version:

php -v

If your website uses PHP-FPM, identify the active PHP-FPM service:

systemctl list-units --type=service | grep php

Restart the appropriate PHP-FPM service during an approved maintenance window.

Important: PHP CLI and PHP-FPM may use different PHP versions. Verify that the extension is installed and enabled for the PHP runtime serving your website.

16. Test Memcached from PHP

Create a temporary PHP test script:

nano /tmp/memcached-test.php

Add:

<?php

$memcached = new Memcached();

$memcached->addServer('127.0.0.1', 11211);

$memcached->set(
    'owned_networks_test',
    'Memcached is working',
    60
);

$value = $memcached->get('owned_networks_test');

echo $value . PHP_EOL;

Run the script:

php /tmp/memcached-test.php

Expected output:

Memcached is working

Remove the temporary script after testing:

rm /tmp/memcached-test.php

Note: This example tests basic connectivity and caching behavior. Production applications should check operation return values and handle cache failures gracefully.

17. Configure Memcached for WordPress

WordPress can use Memcached as a persistent object cache.

Persistent object caching stores reusable application objects between requests, reducing repeated database operations.

To configure Memcached with WordPress:

  1. Install Memcached on the VPS.
  2. Install the PHP Memcached extension.
  3. Verify local connectivity.
  4. Install a WordPress object caching integration compatible with Memcached.
  5. Configure the cache server address and port.
  6. Enable persistent object caching.
  7. Verify that the cache is functioning correctly.

A typical local Memcached connection uses:

Host: 127.0.0.1
Port: 11211

WordPress object cache integrations commonly use an object-cache.php drop-in file.

Important: Installing the PHP extension alone does not enable persistent object caching in WordPress.

Use a maintained, compatible integration and follow its installation instructions.

18. Memcached and WooCommerce

WooCommerce websites can benefit from object caching, particularly when processing frequent product, taxonomy, and database queries.

However, WooCommerce also handles customer-specific information such as:

  • Shopping carts.
  • Checkout sessions.
  • Customer accounts.
  • Order information.
  • Personalized pricing or availability.

Object caching must be configured carefully to avoid serving incorrect or stale application data.

Important: Memcached object caching is different from full-page caching. Customer-specific pages such as cart and checkout pages generally require appropriate exclusions from full-page caching.

Test WooCommerce functionality after enabling or modifying caching.

19. Monitor Memcached Resource Consumption

Use standard Linux monitoring tools to inspect the Memcached process.

Check memory usage:

ps aux | grep '[m]emcached'

Inspect system memory:

free -h

Monitor processes interactively:

top

If installed:

htop

Review Memcached statistics:

memcstat --servers=127.0.0.1:11211

Monitoring should focus on:

  • Process memory consumption.
  • Cache hit and miss trends.
  • Eviction activity.
  • Connection counts.
  • Application response times.
  • Database query load.

For additional Linux monitoring commands, see our Linux VPS monitoring tutorial.

20. Troubleshooting Common Memcached Problems

Memcached service is not running:

sudo systemctl status memcached --no-pager
sudo journalctl -u memcached -n 100 --no-pager

Review configuration changes and check for invalid startup options.

Connection refused:

sudo ss -tlnp | grep 11211

Verify that Memcached is listening on the expected address and port.

PHP cannot connect to Memcached:

Verify that the PHP extension is installed:

php -m | grep -i memcached

Check whether PHP-FPM uses the same PHP version as the command-line environment.

High cache eviction rate:

Review Memcached statistics and evaluate the configured memory allocation.

memcstat --servers=127.0.0.1:11211

WordPress object caching does not work:

Verify that a compatible object cache integration is installed and that it can connect to Memcached.

Memcached consumes too much memory:

Review the configured -m limit and total process memory usage.

Remember that total process memory can exceed the configured item storage limit.

21. Memcached Security Best Practices

  • Keep Memcached and Ubuntu updated.
  • Bind Memcached to localhost whenever possible.
  • Never expose TCP port 11211 directly to the public internet.
  • Disable UDP support unless specifically required.
  • Use private networking for distributed caching deployments.
  • Restrict network access using firewall rules.
  • Allocate memory according to available VPS resources.
  • Monitor cache evictions and application performance.
  • Do not store sensitive information without appropriate application-level protections.
  • Do not rely on Memcached for permanent data storage.
  • Test application behavior after configuration changes.
  • Monitor service availability and resource consumption.

Memcached is designed to accelerate applications, not replace a persistent database or backup system.

22. When Should You Use Memcached?

Memcached is a good choice when:

  • Your application needs simple, high-speed caching.
  • Cached information can be regenerated when necessary.
  • You want to reduce repeated database queries.
  • Your application already supports Memcached.
  • You do not require Redis-specific data structures or persistence.

Redis may be more appropriate when your application requires persistent state, queues, streams, or advanced data structures.

For many PHP and WordPress applications, either technology can provide effective object caching when correctly configured.

The best choice depends on application compatibility, workload characteristics, and operational requirements.

Related Ubuntu VPS Tutorials

Improve Website Performance with Owned Networks

Deploy WordPress, WooCommerce, PHP applications, databases, and caching services on an Owned Networks KVM VPS with full root access and flexible server resources.

Combining Memcached with properly configured PHP applications, efficient database queries, and reliable VPS infrastructure can help reduce server load and improve website responsiveness.

Explore Owned Networks VPS Hosting and deploy your next Linux server today.


Was this answer helpful?

KVM VPS & Dedicated Servers

Deploy a Linux VPS in under 2 minutes — AlmaLinux, Rocky Linux, Ubuntu, Debian. Full root access, KVM virtualization, US and EU locations.

« Back