SystemD Quickstart
A quite handy framework built-in to most Linux distro. SystemD helps in setting up a process that restarts itself on boot, and when it crash. This is what many packages do when apt-installed.
Doing it by hand is not complicated. But I couldn't find a single quickstart source to refer to. This is my public tl;dr notes in setting up systemd that should match most needs.
Let's say we are setting up homebridge
. Replace that name with your service.
The Service File
Describe the service, where's the executable, who's the user that should run it as.
file: /etc/systemd/system/homebridge.service
[Unit]
Description=HomeBridge server # A description
After=syslog.target network-online.target
[Service]
Type=simple
User=pi # A username to run this service as
EnvironmentFile=/etc/default/homebridge #Environment Variable for the service. This is a separate file creating below
# See comments below for more information
ExecStart=/usr/bin/homebridge $HOMEBRIDGE_OPTS #As you'd type in command line. $HOMEBRIDGE_OPTS is from the EnvironmentFile defined below
Restart=on-failure
RestartSec=10
KillMode=process
[Install]
WantedBy=multi-user.target
The Environment File
Many processes are controlled by environments variable. It is usually better to separate those out as a file.
file: /etc/default/homebridge
HOMEBRIDGE_OPTS=-U /var/lib/homebridge
# DEBUG=*
Startup and Logging
A 3 step dance.
# This is to load any changes
# Do this everytime you a file content is changed
sudo systemctl daemon-reload
# Make the service restart every boot
sudo systemctl enable homebridge
# Start up the service
sudo systemctl start homebridge
To see if the service really started up corrrectly.
$ sudo systemctl status homebridge
● homebridge.service - Node.js HomeKit Server
Loaded: loaded (/etc/systemd/system/homebridge.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2019-05-25 17:56:31 BST; 5s ago
Main PID: 13572 (homebridge)
CGroup: /system.slice/homebridge.service
└─13572 homebridge
To see the logs printed out by the service to system out
$ sudo journalctl -u homebridge
May 25 17:56:31 raspberrypi systemd[1]: Started Node.js HomeKit Server.
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] Loaded config.json with 1 accessories and 0 platforms.
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] ---
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] Loaded plugin: homebridge-webos-tv
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] Registering accessory 'homebridge-webos-tv.webostv'
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] ---
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] Loading 1 accessories...
May 25 17:56:34 raspberrypi homebridge[13572]: [2019-5-25 17:56:34] [TV] Initializing webostv accessory...