Penguin Crumbs

Notes and tips from a Linux user

home about this blog
search:  

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.

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.

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). Everything has been tested with systemd version 254.1 on Arch Linux, in September 2023.

Let's create this executable script: /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 truedo
    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 /usr/lib/systemd/system/my_service.service

[Unit]
Description=My first systemd test service

[Service]
Type=simple 
ExecStart=/usr/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 /usr/lib/systemd/system/my_service.service

4. delete the service script:

rm -v /usr/local/bin/my_systemd_service.sh


 
 
Posted on 2023-09-09  
 
⇦  back
 
__________________
 
Copyright © 2019-2023 Marcello Zaniboni