How to configure your first service in systemd
Systemd has always annoyed a lot of people, but you have to get over it, because nowadays almost all distributions have adopted it. So in this post we will see how to configure a simple systemd service, from scratch. Everything has been tested with systemd version 254.1 on Arch Linux and version 249.11 on Ubuntu.
In this guide, all commands must be executed as root, so use "sudo -i" or "sudo su" or whatever you prefer to get a root prompt.
Our example service is a simple bash script that logs the current date and time and a random number to a file in the /tmp directory every 30 seconds. Not very useful actually, but good enough for our purposes.
Let's create this executable script: /usr/local/bin/my_systemd_service.sh (and then don't forget to set the executable flag with "chmod 755 /usr/local/bin/my_systemd_service.sh"):
#!/usr/bin/env bash
# This is my first, simple systemd service
readonly LOG_FILE="/tmp/my_systemd_service.log"
while true; do
tstamp="$(date +"%Y-%m-%d %H:%M:%S")"
echo "$tstamp - $RANDOM" >> "$LOG_FILE"
sleep 30
done
Now we are going to define the configuration by creating the file /etc/systemd/system/my_service.service (some tutorials may suggest you a different folder, such as /usr/lib/systemd/system, but /etc/systemd/system is more appropriate for custom service file):
[Unit] Description=My first systemd test service [Service] Type=simple ExecStart=/usr/local/bin/my_systemd_service.sh [Install] WantedBy=multi-user.target
Remember: the name of this .service file is very important because it will be the name by which systemd will call our service. So in this case we are defining a service named "my_service".
Well, we're almost done: now all we have to do is tell systemd to reload the condiguration and enable the new service when the operating system starts:
systemctl daemon-reload systemctl enable my_service
Congratulations, you just did your first systemd service!!!
Now the service can be controlled with the usual commands that you will surely have already used on Linux:
systemctl start my_service # this starts the service systemctl status my_service # this displays its status systemctl stop my_service # and this... try to guess it
And finally, we close these notes with the commands to go back and uninstall everything, in four steps.
1. stop the service:
systemctl stop my_service
2. disable the service:
systemctl disable my_service
3. delete service definition file:
rm -v /etc/systemd/system/my_service.service
4. delete the service script:
rm -v /usr/local/bin/my_systemd_service.sh
Posted on 2023-09-09
__________________
Copyright © 2019-2024 Marcello Zaniboni