(updated ) by

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.

[Unit]
Description=Describe your service

; Wait till the network is online
After=network-online.target

; Make sure networkd is online
Wants=network-online.target systemd-networkd-wait-online.service

; Time between start attempts.
StartLimitIntervalSec=500

; Limit of number of starts
StartLimitBurst=5

[Service]
; make sure to restart if the process stops
Restart=on-failure
; time til it will try to restart
RestartSec=5s

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

; Any additional environmental variables for this process can be set here
Environment=CSP_CAPTURE_LOG=/log/csp-capture.log

[Install]
WantedBy=multi-user.target

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.