The One and the Many

systemd user services

systemd gets a bad rap, but it makes some use cases super easy. An example is the ability to configure and run services as a regular user. Once you've configured your user, you can set up services without involving root.

Why would you want to do this? One reason is that it's nice to keep everything related to a user within their home directory. As well, when something does not need elevated access, it's nice to be able to manage it without that access. In the past I've resorted to hacks like running things in tmux with @reboot via cron. Letting systemd manage things is cleaner and more resilient.

In this post I'll describe how to work with user services. I'm working on a Debian stretch VM.

Enabling user services

I had to install the dbus-user-session package:

root# apt-get install dbus-user-session

Before doing this I was seeing an error:

Failed to connect to bus: No such file or directory

To confirm user level access is working, look at systemd's status:

will$ systemctl --user status

You should also see a /lib/systemd/systemd --user process running under your user when you log in.

Since we want our services to stay running when we log out, we need to allow that:

root# loginctl enable-linger will

We should now be able to define and run services without root access.

Running a user service

To do this, write a systemd service file as usual, but put it in $HOME/.config/systemd/user. In this example I'm configuring a service called ircord:

will$ cat .config/systemd/user/ircord.service
ExecStart=/home/will/ircord [..]


Enable the service and start it:

will$ systemctl --user enable ircord
will$ systemctl --user start ircord

And that's it!

It's awesome how easy writing service scripts is with systemd. I remember writing SysV init scripts by hand in the past, and I never felt like I got them quite right. With systemd I can write a few lines and feel confident it will work.