Installing and configuring Memcached on Ubuntu

How to install and configure Memcached on an Ubuntu server.

Memcached is an in-memory caching service based on a hash table. It's used to cache web page output, database query results, and other data with a defined expiry time. Data is accessed by key.

Memcached can also be installed in one click when placing an order — see One-Click-Apps for details.

Installation

Update the system:

apt-get update && apt-get upgrade

Install Memcached and the PHP module:

apt-get install memcached php5-memcache

Verify that the daemon is running:

netstat -tap | grep memcached

Expected output:

tcp    0    0 localhost:11211    *:*    LISTEN    21488/memcached

Configuration

By default, Memcached listens on port 11211 at 127.0.0.1. To change any of these settings, edit /etc/memcached.conf.

Key parameters:

  • -l 127.0.0.1 — the IP address the daemon listens on. Change this to an external IP if outside access is required.
  • -m 256 — memory allocated for the cache in MB.
  • -p 11211 — the port the daemon listens on.

After making changes, restart Memcached:

/etc/init.d/memcached restart

If Apache is installed, restart it to load the module:

/etc/init.d/apache2 restart

Firewall configuration

Allow connections to Memcached from a trusted IP range:

iptables -A INPUT -p tcp --destination-port 11211 -m state --state NEW -m iprange --src-range 111.161.1.10-111.161.1.15 -j ACCEPT
iptables -A INPUT -p udp --destination-port 11211 -m state --state NEW -m iprange --src-range 111.161.1.10-111.161.1.15 -j ACCEPT

Allow all outgoing connections:

iptables -P OUTPUT ACCEPT

Allow incoming connections on port 80 from anywhere:

iptables -A INPUT --dport 80 -j ACCEPT

Allow ports 22 and 5432 from a specific IP only:

iptables -A INPUT -m multiport --dports 22,5432 -s IP_ADDRESS -j ACCEPT

Help

If you have any questions or need assistance, please contact us through the ticket system — we're always here to help!

Need help?Our engineers will help you free of charge with any question in minutesContact us