Tag Archives: socket

use unix socket instead of tcp connection for memcached to speed up web servers

By default, memcached is listening on port 11211 for all connections. But for a single server, it’s better to config memcached to use unix socket which improve the performance and reduce the legacy.

On freebsd, it’s easy to change from TCP/IP to unix socket. But there are some steps you need to pay more attention.

1. Modify rc.conf to force memcached to use unix socket.

memcached_flags="-m 2048 -s /tmp/memcached.sock"

2. Modify the connection string in your php files.
For TCP connection, use

$_config['memory']['memcache']['server'] = '127.0.0.1';
$_config['memory']['memcache']['port'] = 11211;

If you are using php-memcache, you should change it to

$_config['memory']['memcache']['server'] = 'unix:///tmp/memcached.sock';
$_config['memory']['memcache']['port'] = 0;

If you are using php-memcached, you should change it to

$_config['memory']['memcache']['server'] = '/tmp/memcached.sock';
$_config['memory']['memcache']['port'] = 0;

3. Another thing I found in Freebsd is that if you force memcached to use unix socket, every time you restart the service, memcached will change the socket file permission to 550 which means php can’t connect to the socket file. So you need to grant php user access to that file.

chmod 777 /tmp/memcached.sock

You need to do this each time after you restart memcached.