How to run a user service with systemd
By Mikael Ståldal
Most Linux systems uses systemd as init and service manager nowadays.
You can use systemd to start your services, so that they are automatically restarted if they crash, and automatically started when the system boots. You can even do this as a regular user, without root access (then the service will run with permissions of your user), and have it automatically started when the system boots without you having to login.
- Create the
~/.config/systemd/userdirectory if necessary:
mkdir -p ~/.config/systemd/user
- Create a service unit configuration file
for your service in that directory
~/.config/systemd/user/myservice.service:
[Unit]
Description=MyService
[Service]
Type=exec
LoadCredential=my-password:%h/myservice.pw
ExecStart=%h/.local/bin/myservice -password-file ${CREDENTIALS_DIRECTORY}/my-password
Restart=on-failure
NoNewPrivileges=true
AppArmorProfile=myservice
[Install]
WantedBy=default.target
- Load the service definition:
systemctl --user daemon-reload
- Enable the service:
systemctl --user enable myservice.service
- Start the service
systemctl --user start myservice.service
- Enable starting the service on boot without login (you might need to run this as root):
sudo loginctl enable-linger
This will provide the service with credentials from file ~/myservice.pw, and run the service with AppArmor
profile myservice (which you must create and load first).
Then you can stop the service with systemctl --user stop myservice.service and restart it with systemctl --user restart myservice.service.
This has been tested on Debian Linux.