Using systemd to handle restarts

systemd is a common system daemon that works with running services in linux. A common scenario is wanting services to automatically start on boot or to restart if they crash. Lots of things can happen to computers. You want your service to be resistant to a minimal degree.

Keeping a service up minimally can happen through a simple .service file. I use this pattern to make sure services stay up after restarts of the machine or handling errors in the service which can take it down.

Description=Describe your service

; Wait till the network is online

; Make sure networkd is online systemd-networkd-wait-online.service

; Time between start attempts.

; Limit of number of starts

; make sure to restart if the process stops
; time til it will try to restart

; Your main executable to run
ExecStart=/usr/bin/docker run -e CSP_CAPTURE_LOG -v /var/log/csp-capture:/log -p 12345:12345

; Any additional environmental variables for this process can be set here


Once you finish you must update the daemon for systemd (systemctl daemon-reload). Then you should be able to run the service to see if works.

sudo systemctl start myservicefile.service

Then you can “enable” the service.

sudo systemctl enable myservicefile.service

Next, you want to harden your service files. You may not need to do much but it’s a good thing to look into. A thread on hacker news has good information on how to do this. Contains other posts with more information.

Specifically look into systemd-analyze security myservicefile.service which will check for possible hardening you can do. You want to make sure you don’t expose too much and limit what this process can do, at least from the systemd service level.