Monday, March 1, 2010

Installing memcached on CentOS 5.x

Memcached is a distributed memory object caching system - as quoted from

In other words, it is simply a cache for common database queries and typically reduces database load by caching the mentioned queries.

It is not part of the standard CentOS distro, so installation of the DAG repositories was necessary.

0. Login as root on your webserver(s)

This install specific to the 32-bit version of CentOS 5.x

1. Get the rpmforge rpm (if not already installed)

2. Install the rpmforge rpm
rpm -Uvh rpmforge-release-0.3.6-1.el5.rf.i386.rpm

3. Install memcached and other packages required
yum install --enablerepo=rpmforge memcached php-pecl-memcache

4. Modify php.ini
nano /etc/php.ini

add line under Dynamic Extension section.

5. Create memcached configuration file
nano /etc/sysconfig/memcached
Add to file:
#  Specify Port
#Specify User for service to run.
#Specify maximum number of connections
#Set Cache size based on Memory available

#Specify which interface to listen to - Security Measure

6. Add the memcached user (the same username entered in step 5)
useradd memcached

7. Start the memcached daemon and set to automatically start on reboot
service memcached start
chkconfig memcached on

8. Test memcached
Original Script located at
Create script in site root, or other preferred location.
touch /var/www/html/memcachedtest.php

Paste the following code:

//memcached simple test
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$key = md5('42data');  //something unique
for ($k=0; $k<5; $k++) {
$data = $memcache->get($key);
    if ($data == NULL) {
        $data = array();
        //generate an array of random shit
        echo "expensive query";
        for ($i=0; $i<100; $i++) {
            for ($j=0; $j<10; $j++) {
                $data[$i][$j] = 42;  //who cares
    } else {
        echo "cached";

Run to see if it works
You should see "Expensive Query"
If memcached works, you should see "Cached Cached Cached" upon refreshing the page.