linux systemd service

In this tutorial as an example we create on a GNU/Linux operating system a service with systemd that runs the SimpleHTTPServer written in Python on port 8000 of the local server.
For security reasons this server should NOT be run in production environments.

Table of Contents

Example of using systemd on GNU/Linux

Systemd is an init system used in GNU/Linux distributions tobootstrap the user space and then manage all its processes. It is currently the default init system in most GNU/Linux distributions.

Systemd works withunits which are resources (network, usb, etc.) governed byunit files stored in /lib/systemd/system which contain sections and directives.

Types of drives

There are 12 unit types:

Services (.service): services
Target: drive group
Automount: filesystem auto-mount point
Device: kernel device names, which can be seen in sysfs and udev
Mount: filesystem mount point
Path: file or directory
Scope: external process not started by systemd
Slice: A unit of management processes
Snapshot: saved state of systemd
Socket: IPC (inter-process communication) socket
Swap: Swap file
Timer: systemd timers

To name a unit file you use the format<resource_name>.<unit_type>(<resource_name>.<unit_type>) for example:

reboot.service

A target looks like a SysV Init runlevel: for example graphical.target is similar to runlevel 5.

Creating a service with systemd

The steps to create a service in systemd are the following:
1) We open a terminal and create the file with the instructions for the new service:

vim /lib/systemd/system/system/example.service

[Unit]
Description=Example
After=network.target
StartLimitIntervalSec=0

Service] [Service
Type=simple
Restart=always
RestartSec=1
User=user
ExecStart=/usr/bin/env python3 /user/example.py

[Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install
WantedBy=multi-user.target

Here you have to change the user name and the path to the python script with your data. Save and save the changes.

Create a Python script

2) In the directory /user/ (replace the path with your path written in the previously created file) program the following python script:

vim example.py

import http.server
import socketserver

PORT = 8000

handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), handler) as httpd:
print("Server started at localhost:" + str(PORT))
httpd.serve_forever()

Save and save the changes.

Starting a systemd service

3) We start the service, verify that it works correctly and enable it to run automatically:

sudo systemctl start example
sudo systemctl status example
sudo systemctl enable example

Finally we open a browser and write the path to the SimpleHTTPServer replacing the IP with yours:

http://10.0.2.2:8000/

Creating a timer with systemd

In this example we will create a timer on GNU/Linux operating systems to run a bash script.

The steps to create a timer are the following:
1) We open a terminal and create the file with the instructions for the new service:

vim /lib/systemd/system/system/date.service

[Unit]
Description=A test

Service] [Service
Type=oneshot
ExecStart=/bin/bash /user/date.sh

[Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install
WantedBy=multi-user.target

Here you must change the user name and the path to the bash script with your data. Save and save the changes.

2) In the directory /user/ (replace the path with yours written in the file previously created) we program the following script:

vim date.sh

#!/bin/bash
DATE=$$(date '+%Y-%m-%d %H:%M:%S'); echo -e "$DATE" >> /user/log.log
echo -e "Hello world" >> /user/log.log

Save and save the changes.

we give it execution permissions with:

chmod 755 date.sh

3) Now the timer file must be created:
vim /lib/systemd/system/system/date.timer

[Unit]
Description=Runs every 1 minutes fecha.sh

[Timer]
OnCalendar=*:0/1

[Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install
WantedBy=timers.target

Save and save the changes.

4) We start the service, verify that it works correctly and enable it to run automatically:

sudo systemctl start date
sudo systemctl status date
sudo systemctl enable date

If we make any changes to the systemd files, the following command must be executed:

systemctl daemon-reload

Some useful commands for systemd

Location of drive files:

/etc/systemd/system/
/usr/lib/systemd/system/

List of running drives:

systemctl list-units -type [unit name]
systemctl list-unit-files -type=service
systemctl list-units -type service -all

Checking the status of a service:

systemctl status motd-news.service

References

Debian Wiki. https://wiki.debian.org/Debate/initsystem/systemd
Atareao.es. How to create a service with systemd. https://www.atareao.es/tutorial/trabajando-con-systemd/como-crear-un-servicio-con-systemd/
Wikipedia. systemd. https://es.wikipedia.org/wiki/Systemd
Digital Ocean Tutorial. https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units-es

The images used in the covers, unless otherwise indicated, are free and/or royalty-free. They belong to various authors and were downloaded from Unsplash, Pixabay, and/or Pexels.

 

If you are looking for a trainer to run this course or another training activity (webinar, workshops, bootcamps, etc.) in your organisation, you can find me through the contact page. Thank you very much.

If you liked the article you can help me by donating with cryptocurrencies. Thank you!!!