By default memcached has no authentication on its plain-text protocol, so it’s advised to make the ports of the service public only to those systems that need to access it. (Memcached does support SASL authentication when built with --enable-sasl and started with -S, but only over the binary protocol.) 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
~# systemctl enable memcached
(On RHEL/CentOS 6 and older, that second command was chkconfig memcached on. RHEL/CentOS 7+ replaced the old init scripts with systemd, so use systemctl there.)
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.
~# systemctl start memcached
(On older init-based systems that was /etc/init.d/memcached start.)
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:*