systemd
An init system on Linux, used on Ubuntu and other distros.
Cheatsheet
Commands
# reload config files
sudo systemctl daemon-reload
# the full name is 'foo.service'
# '.service' is assumed if not specified
sudo systemctl start foo
sudo systemctl stop foo
sudo systemctl restart foo
sudo systemctl status foo
# view config
sudo systemctl cat foo
# view logs
sudo journalctl -u foo
Non-root services
Set-up (courtesy of Stack Overflow):
- Add your user to the group:
sudo usermod -a -G systemd-journal $USER - Log back in.
mkdir -p ~/.config/systemd/user- Put your service files in that directory. Remove any
UserorGroupdirectives. - Set up lingering so services can run without logging in:
loginctl enable-linger $USER systemctl --user daemon-reexec
Then:
systemctl --user daemon-reload
systemctl --user start foo
journalctl --user-unit foo
Service file
- Man pages at
man 5 systemd.unitandman 5 systemd.service - Unit section options
- Service section options
- More options
[Unit]
Description=Grafana
[Service]
ExecStart=/usr/bin/grafana server
User=ian
WorkingDirectory=/home/ubuntu/grafana
Environment="MY_VAR=value"
Environment="MY_VAR2=value"
Restart=always
# if restarts more than 3 times in 60 seconds, don't try to restart
# NOTE: before systemd v230, called `StartLimitInterval`
StartLimitIntervalSec=60s
StartLimitBurst=3
# wait 5 seconds in between restarts
RestartSec=5s
[Install]
# start service on system start-up
WantedBy=default.target
After versus Requires
Afterestablishes order: if service B hasAfter=A, and service A and B are both being started up (e.g., because they both haveWantedBy=default.target), then service A will be started before service B.Requiresestablishes dependency: if service B hasRequires=A, and service B is being started up, then service A will also be started up (not necessarily before service B, unlessAfteris also specified).Wantsis likeRequiresbut creates a weak dependency; systemd will try to start the other service but will still run the first service even if the other fails.
Bibliography
- "systemd, 10 years later: a historical and technical retrospective" (V.R., 2020)
- "The Tragedy of systemd" (Benno Rice @ YouTube, 2016)