Creating Systemd Daemon the Right Way

September 20, 2021

Simple note, mostly for myself, how to create new SystemD daemon (service, unit, whatever), so I don’t need to search in internet every time.

I don’t like SystemD, but it’s everywhere, anywhere, spread his tentacles into every computer, climbed into every crevice… Ahem…

Create a daemon

Path to systemd daemons is: /etc/systemd/system/. All daemons must be .service extention.

A daemon, that will restart itself, if crash:

[Unit]
Description=Demo service
# You can see list of all targets by execute
# ls -1 /etc/systemd/system/ | grep target
After=network.target

[Service]
Type=simple
Restart=always
RestartSec=1
ExecStart=/usr/bin/something
# or
ExecStart=/usr/bin/env python /path/to/something.py

# Or just use bash script ;) You need it anyway,
# if you want to start-stop-reload with specific options.
# I.e.:
ExecStartPre=/usr/bin/zram start
ExecStart=/usr/bin/zram enable
ExecStop=/usr/bin/zram stop

[Install]
WantedBy=multi-user.target

A “single shot” daemon:

[Unit]
Description=Swap with zram
After=multi-user.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStartPre=/usr/bin/zram start
ExecStart=/usr/bin/zram enable
ExecStop=/usr/bin/zram stop

[Install]
WantedBy=multi-user.target

After creating the file, execute:

systemctl enable your-daemon.service
systemctl start your-daemon.service

To check if daemon working correctly, execute journalctl -xe, because SystemD will not give you any feedback. “Thanks”, Pottering.