Creating service files for systemd

Systemd is designed to improve on the Linux startup process & init daemons by consolidating them to make them simpler. As systemd is quite new, not all Linux distributions provide systemd units for a few services as they are still using traditional init systems such as SysV init/Upstart.

Included are a few service files that I’ve created for my own use.

Quick Guide

touch /etc/systemd/system/name.service
chmod 664 /etc/systemd/system/name.service
systemctl daemon-reload
systemctl start name.service
systemctl enable name.service

tl;dr

  • create a service file (as root)
  • give it appropriate permissions
  • edit service file for desired functionality
  • start service
  • enable service on boot

ZNC

The service file is taken from znc documentation with a few modifications to ensure that the daemon restarts upon failure.

  • starts on boot, after the network is up
  • daemon runs as user znc
  • restarts upon failure, with a 3 second grace period
[Unit]
Description=ZNC, an advanced IRC bouncer
After=network-online.target

[Service]
ExecStart=/usr/local/bin/znc -f --datadir=/var/lib/znc
User=znc
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

rtorrent

It is recommended to run this as a system service rather than an user service due to issues with Debian. The config was mostly borrowed from Arch Linux’s excellent wiki.

  • starts on boot, after the network is up
  • daemon runs as user rtorrent
  • restarts upon failure, with a 3 second grace period
  • relies on screen to daemonize itself
[Unit]
Description=rTorrent Daemon
After=network.target

[Service]
Type=forking
KillMode=none
ExecStart=/usr/bin/screen -d -m -fa -S rtorrent /usr/local/bin/rtorrent
ExecStop=/usr/bin/killall -w -s 2 /usr/local/bin/rtorrent
User=rtorrent
WorkingDirectory=/var/lib/rtorrent/downloads
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

nginx

When using nginx mainline on Debian, a service file had to be created as Debian Jessie does not currently have one. The following file was generated with help from the nginx resources.

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

External resources