Installing and configuring Memcached on CentOS
How to install and configure Memcached on a CentOS 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:
yum update
Install Memcached:
yum install memcached
Configuration
Open the configuration file:
vim /etc/sysconfig/memcached
Make sure the following parameters are present:
PORT="11211"
USER="memcached"
MAXCONN="256"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1"
Parameter descriptions:
PORT— the port Memcached listens on. Default is11211.USER— the user account the daemon runs under.MAXCONN— the maximum number of simultaneous connections.CACHESIZE— memory allocated for the cache in MB.64MB works well for most small and medium sites. For high-traffic servers, consider increasing this to512or1024.OPTIONS="-l 127.0.0.1"— restricts Memcached to localhost only, blocking external connections. The default value isINADDR_ANY(all interfaces).
Enable Memcached at startup and start the service:
systemctl enable memcached
systemctl start memcached
Installing the PHP extension
Install the required dependencies:
yum install php-pear pecl_http php-devel
Install the extension via PECL:
pecl install memcache
If PECL asks about session handler support, press Enter to accept the default:
Enable memcache session handler support? [yes]
Restart your web server. For php-fpm:
service php-fpm reload
For Apache:
systemctl restart httpd
Verifying the setup
Check that the Memcached daemon is running:
ps -aux | grep memcached
Verify the service settings:
echo "stats settings" | nc localhost 11211
To confirm the PHP extension is active, create a phpinfo file:
echo "<?php phpinfo(); ?>" > /var/www/html/php_info.php
Open it in a browser and check that the memcache section appears in the output.
Firewall configuration
To allow connections to Memcached from a trusted IP range, add the following iptables rules:
iptables -A INPUT -p tcp --destination-port 11211 -m state --state NEW -m iprange --src-range 192.168.1.10-192.168.1.15 -j ACCEPT
iptables -A INPUT -p udp --destination-port 11211 -m state --state NEW -m iprange --src-range 192.168.1.10-192.168.1.15 -j ACCEPT
Help
If you have any questions or need assistance, please contact us through the ticket system — we're always here to help!