Memcached Distributed Setup on Ubuntu 24.04
Memcached is a single-node daemon; distribution is handled by the client. This guide shows how to run multiple Memcached instances and configure clients to distribute data across them.
Step 1 – Run multiple Memcached instances
# Instance 1 on port 11211
memcached -d -l 192.168.1.10 -p 11211 -m 512 -t 4 -u memcache
# Instance 2 on 192.168.1.11:11211
memcached -d -l 192.168.1.11 -p 11211 -m 512 -t 4 -u memcache
Step 2 – systemd unit for each instance (example)
Create /etc/systemd/system/[email protected]:
[Unit]
Description=Memcached instance %i
[Service]
Type=forking
ExecStart=/usr/bin/memcached -d -l 127.0.0.1 -p %i -m 256 -t 4 -u memcache
PIDFile=/run/memcached/memcached-%i.pid
[Install]
WantedBy=multi-user.target
systemctl enable --now memcached@11211
systemctl enable --now memcached@11212
Step 3 – PHP client consistent hashing
$mc = new Memcached();
$mc->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$mc->addServers([
['192.168.1.10', 11211],
['192.168.1.11', 11211],
['192.168.1.12', 11211],
]);
Step 4 – Monitor across all nodes
for host in 192.168.1.10 192.168.1.11 192.168.1.12; do
echo -n "$host: "
echo "stats" | nc $host 11211 | grep -E 'curr_items|bytes '
done