How to Install and Configure Memcached on CentOS 7
Introduction
Memcached is an open-source, distributed, in-memory object caching system. It is mainly used for speeding up dynamic web applications by storing chunks of data from the results of database calls and page rendering.
In this guide, we will install and secure Memcached on CentOS 7.
##Installing Memcached
First, update the system:
yum update -y
Next, install the official Memcached package memcached
; as well as libmemcached
, which provides several utilities to work with Memcached:
yum install -y memcached libmemcached
Memcached will now be installed as a service.
To start Memcached at boot, use the systemctl
command:
systemctl enable memcached
##Configuring Memcached
Let's bind Memcached to the local interface and disable the UDP port to avoid potential DDOS attacks. Open the /etc/sysconfig/memcached
file in your favorite editor:
nano /etc/sysconfig/memcached
Find this line in the file:
OPTIONS=""
Change it to the following:
OPTIONS="-l 127.0.0.1 -U 0"
Save the file and exit the editor.
Restart Memcached to apply your changes:
systemctl restart memcached
You can ensure that it is running by using systemctl
:
systemctl status memcached
The output will resemble the following:
● memcached.service - Memcached
Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
Active: active (running) since Thu 2019-04-04 17:01:41 UTC; 8s ago
Main PID: 31312 (memcached)
CGroup: /system.slice/memcached.service
└─31312 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 1024 -l 127.0.0.1 -U 0
Apr 04 17:01:41 docs systemd[1]: Started Memcached.
You can verify Memcached is bound only to the local interface and listening only to TCP connections with the ss
command:
ss -plunt | grep memcached
tcp LISTEN 0 128 127.0.0.1:11211 *:* users:(("memcached",pid=31312,fd=26))
There are also a few other options that can be modified in the /etc/sysconfig/memcached
configuration file:
CACHESIZE
: Caps the amount of memory available to Memcached. The default is 64 MB.PORT
: Specifies on which port Memcached should listen. The default port is11211
.USER
: Specifies which user the service will use to run. By default, the service will run asmemcached
.MAXCONN
: Caps the number of concurrent connections. The default is1024
.
##Verifying Memcached Setup
Now, you can verify the set up using the memstat
command from the libmemcached
package:
memstat --servers="localhost"
The output will resemble the following:
Server: localhost (11211)
pid: 31312
uptime: 385
time: 1554397684
version: 1.4.15
libevent: 2.0.21-stable
pointer_size: 64
rusage_user: 0.006269
rusage_system: 0.014105
curr_connections: 1
...
##Conclusion
In this guide, we covered how to install and configure Memcached and used memstat
to fetch stats. The libmemcached
package also comes with a few other utilities that can aid in interacting with Memcached.