Quick tip: multiple memcached instances with systemd – the proper(er) way

Install memcached

apt install memcached

Copy the default unit file to /etc/systemd/system/

cp /lib/systemd/system/memcached.service /etc/systemd/system/memcached@.service

Change the new unit file (/etc/systemd/system/memcached@.service) as follows:

[Unit]
Description=memcached daemon (instance %i)
After=network.target
Documentation=man:memcached(1)

[Service]
ExecStart=/usr/share/memcached/scripts/systemd-memcached-wrapper /etc/memcached_%i.conf

[Install]
WantedBy=multi-user.target

Note the changes in Description and ExecStart (path to config).

Now, create new config files for all the instances you need:

cp /etc/memcached.conf /etc/memcached_moodle-session.conf

cp /etc/memcached.conf /etc/memcached_moodle-appcache.conf

Modify them to use unique port

-p 11211

Reload systemd

systemctl daemon-reload

Stop and disable the old memcached service, then start and enable new ones:

systemctl stop memcached.service

systemctl disable memcached.service

systemctl start memcached@moodle-session.service

systemctl enable memcached@moodle-session.service

systemctl start memcached@moodle-appcache.service

systemctl enable memcached@moodle-appcache.service

3 comments

  1. This is just what I need… BUT shouldn’t you also update /etc/systemd/system/memcached@.service for the instance-specific pid?

    i.e. have this line too:

    PIDFile=/var/run/memcached/memcached_%i.pid

    1. This article was written for Debian 9 where pidfile wasn’t used for memcached by default.

      For Debian 10 and Ubuntu 18.04 you have to change the PIDFile in the unit file:
      “PIDFile=/var/run/memcached/memcached_%i.pid”
      and in memcached config.

      In my case I’d change the file
      “/etc/memcached_moodle-session.conf”
      to contain
      “-P /var/run/memcached/memcached_moodle-session.pid”
      and file
      “/etc/memcached_moodle-appcache.conf”
      to contain
      “-P /var/run/memcached/memcached_moodle-appcache.pid”

      1. Ah yes, I forgot to mention the two .conf files. I had this running unpredictably for years without correctly setting the PIDFile entry but only just worked out what was wrong, so now it’s perfect.

        Very useful guide. Thanks.

Leave a comment

Your email address will not be published. Required fields are marked *