Writing service files in systemd

image source
image source

Systemd may not be the most popular init system out there, and it still manages to annoy me every now and then, but I had a chance to play with it at work recently. A deeper dive into it has left me a little happier with how it handles things.

My requirement was to daemonize a service and have it running at startup. The service has a few command line arguments, and also needs some environment variables set. The command line args could change but should not expect someone to reconfigure the init script. Systemd supported all these requirements out of the box.

Here is what the service file looked like:

[Unit]
 Description=myservice
[Service]
 Environment="LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH"
 EnvironmentFile=/etc/<somefile.cfg>
 ExecStart=/usr/bin/myservice ${arg1} ${arg2} ${arg3}
[Install]
 WantedBy=multi-user.target

The EnvironmentFile has name value pairs of the command line arguments:

arg1=foo
arg2=bar
arg3=baz

There are numerous others configuration parameters for the service. For instance, set Type=oneshot if the application is not a daemon and is going to exit immediately.

Use ExecStartPost for running additional scripts after the first one starts (e.g. maybe you want to write to a pidfile). ExecStartPre, ExecStopPost and ExecStopPre also exist.

The unti file must be present in /etc/systemd/system. To make it run on subsequent boots:

systemctl enable myservice

To start the service:

systemctl start myservice

To check the service’s logs:

journalctl -u myservice

Further reading:

Leave a Reply