Writing a Systemd Service File
Writing a systemd service file
Suyash Singh
Posted by Suyash Singh
on October 8, 2022

Systemd is the ubiquitous System Management Daemon present by default in all the popular linux distros, it is considered as the faster & better replacement for init.d, the initialization daemon for many old generation linux distros.

If we want to autostart certain servers or daemon processes on system boot, we need to create a service unit file and enable it using the controller for systemd — systemctl.

Let’s take a realistic example, let’s say we want to host our own Teamcity server to establish CI for our personal projects. If we want to autostart it on system boot we would need to create a systemd service unit for it:

$ sudo vim /usr/lib/systemd/system/tcserver.service
 
[Unit]
Description=This unit will start after internet connection
After=network-online.target
Wants=network-online.target
 
[Service]
Restart=always
Type=simple
ExecStart=/opt/TeamCity/bin/startup.sh
User=tcadmin
 
[Install]
WantedBy=multi-user.target

This would run the /opt/teamcity/bin/startup.sh script as tcadmin user on system start. It is a common practice to use ExecStartPre, ExecStartPost, ExecStartPost, ExecCondition, ExecReload, ExecStop etc. along with ExecStart to manage the lifecycle of our services. Finally we need to register the above service unit file with systemd:

$ sudo systemctl enable tcserver

Bonus tip

To verify our configuration following commands offer quick help:# start our service: tcserver in this example

$ sudo systemctl start <service_name>
 
# check logs to understand the problems if any
$ journalctl -u <service_name>

Further reading