Creating Systemd Service Files

systemd is used in many mainstream Linux distributions like Arch Linux, CentOS, Debian/Ubuntu, RedHat/Fedora, openSuse, Slackware, CoreOS and more. It provides an easy way to manage and control services and a simple method of creating your own services. This will cover the process of creating and managing your own custom service.

You should copy your .service file to /etc/systemd/system. Do not symlink it. One, you can't run systemctl enable because you it will not follow a symlink. Two, it potentially opens up a security risk (e.g. a shell). For example, you run your service as a low privilege user but you are symlinking the .service file. Someone finds a flaw in your service where they are able to overwrite or modify files. They can turn that in to code execution by modifying the .service file that your low privilege user has access to and changing the command that is run (ExecStart). When the service is restarted the attackers command is run. This is also why you should not run the service as root.

Note that you can also put the files in /usr/lib/systemd/system/ but that should be reserved for system level packages. Anything in /etc/systemd/system will override it and that is where user changes should go.

The .service File

Create a .service file in the systemd folder. For example /etc/systemd/system/my_daemon.service. Here is an example .service file.

Description=My Miscellaneous Service

# Another Type option: forking
ExecStart=/home/nanodano/my_daemon --option=123
# Other Restart options: or always, on-abort, etc


There are more options you can specify. For example, in addition to ExecStart you can specify ExecStop and ExecReload to control what happens when stopping and restarting. Those are not required though. If you omit the ExecStop option, it is smart enough to know it should kill the process. If you need a more graceful shutdown though, specify that with ExecStop. To see some more options, look at man systemd.service in your distribution.'s man systemd.service .

# Read all the service options
man systemd.service

Controlling the Service

# Control whether service loads on boot
systemctl enable
systemctl disable

# Manual start and stop
systemctl start
systemctl stop

# Restarting/reloading
systemctl daemon-reload # Run if .service file has changed
systemctl restart

View Status/Logs

# See if running, uptime, view latest logs
systemctl status
systemctl status [service_name]

# See all systemd logs

# Tail logs
journalctl -f

# Show logs for specific service
journalctl -u my_daemon.service