Linux: Start user processes or systemd units at boot time with systemd

Hi,

systemd based system have the ability to start user processes in background and as daemon even the user isn’t logged on to the system.

Instead of defining a system systemd unit which switches the user at process start time, for example

[Service]
...
User=michael
Group=michael

systemd user units can also be started and stopped by the user itself.

You just have to create a systemd unit.

michael@debdev ~# mkdir -p $HOME/.config/systemd/user
michael@debdev ~# vi $HOME/.config/systemd/user/myprocess.service

Content of myprocess.service is like

[Unit]
Description=My Process
After=multi-user.target

[Service]
RemainAfterExit=True
ExecStart=/home/michael/bin/myProcess

[Install]
WantedBy=default.target

Important is the WantedBy=default.target option!
Enable the unit and start it

michael@debdev ~# systemctl --user enable myprocess.service
michael@debdev ~# systemctl --user start myprocess.service

If you got an error

michael@debdev ~# systemctl --user enable myprocess.service
Failed to connect to bus: Access denied

Then usually the DBUS_SESSION_BUS_ADDRESS environment variable is not set to the correct user path

michael@debdev ~# echo $DBUS_SESSION_BUS_ADDRESS
unix:path=/run/user/0/bus

Here the path is set to the root users bus address. This can happend if you switch to the user by su. Set the correct address before calling systemctl as user

michael@debdev ~# export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus

If you want to start the unit at boot time you have to enable linger for the user.

root@debdev ~# loginctl enable-linger michael

Michael

Advertisment to support michlstechblog.info

One thought on “Linux: Start user processes or systemd units at boot time with systemd”

  1. In my case it was the WantedBy=defaut.target.

    I had a system where it worked and other where it failed due to it. Probably differences in the targets available I guess.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.