Letting memcached only listen on localhost on CentOS/RHEL

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, February 18, 2012

Follow me on Twitter as @mattiasgeniar

Since memcached doesn’t have authentication (yet), it’s advised to make the ports of the service public only to those systems that need to access it. That means firewalling the default port 11211. But if you’re only running memcached on a local machine which needs local access, you can also make memcached only listen on the local 127.0.0.1 IP. Doing so, remote access is not possible.

First, install memcached.

~# yum install memcached
~# chkconfig memcached on

After the installation, the default config file looks like this.

~# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""

If you start memcached now, it would listen to all available interfaces.

~# netstat -an | grep ":11211"
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN
udp        0      0 0.0.0.0:11211               0.0.0.0:*

To prevent that, change the last line with the OPTIONS variable to this (that’s lower case L in the options).

~# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1"

And start memcached.

~# /etc/init.d/memcached start
Starting memcached:                                        [  OK  ]

If you now check your ports, you’ll notice it only listens on localhost (127.0.0.1).

~# netstat -an | grep ":11211"
tcp        0      0 127.0.0.1:11211             0.0.0.0:*                   LISTEN
udp        0      0 127.0.0.1:11211             0.0.0.0:*


Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.