How to create a "user service" with systemctl
Learn how to create a background task and run it as a user service using systemctl
Systemd is a system and service manager for Unix-like operating systems, It is responsible for starting all processes during the system boot. Systemctl is a Linux command used to control and configure systemd.
In this post, we are exploring a systemctl functionality that allows unprivileged users to run processes in the background.
Create a background task
Let's create first the task we want to run in the background, we will use this app.sh
script written in Bash:
#!/bin/bash
while true ; do
echo `date` >> /home/marco/app.log
sleep 60
done
As you can see, it writes the date
into the app.log
file every 60 seconds. Put the script in your home folder and grand execute permissions:
chmod 700 app.sh
Create the systemctl user service
Systemctl will look for user service files in this path ~/.local/share/systemd/user/
. Create the directory and the app.service
file:
mkdir -p ~/.local/share/systemd/user/
vim ~/.local/share/systemd/user/app.service
The following configuration describes how to start the app.sh
script. Do not forget to change the absolute path of the file according to your username.
[Unit]
Description= app user service
[Service]
Type=simple
WorkingDirectory=/home/marco/
ExecStart=/home/marco/app.sh
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
Launch the user service
When launching a user service you have to add the --user
parameter to the systemctl command:
systemctl --user start app.service
This will enable systemctl to discover the app.service
in your home directory, there is no need to invoke the command with sudo
.
The background task is up and running, we can check for the log output:
tail -f app.log
A new line will appear every 60 seconds.
To keep the user service running over reboot and when you log out from your server you need to enable the service:
systemctl --user enable app.service
Edit the logind.conf
file:
sudo vim /etc/systemd/logind.conf
Make sure that KillUserProcesses
variable is set to no
:
[Login] KillUserProcesses=no
Finally, restart the logind service:
sudo systemctl restart systemd-logind
As for system services, you can check the status and stop the service:
systemctl --user status app.service
systemctl --user stop app.service
Conclusions
In this post, I have shown you how to create and run a systemctl user service. User services are convenient to run processes in the background and don't require administrative privileges.