home blog notes portfolio Ian Fisher

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 logs
sudo journalctl -u foo

Non-root services

Set-up (courtesy of Stack Overflow):

  1. Add your user to the group: sudo usermod -a -G systemd-journal $USER
  2. Log back in.
  3. mkdir -p ~/.config/systemd/user
  4. Put your service files in that directory. Remove any User or Group directives.
  5. Set up lingering so services can run without logging in: loginctl enable-linger $USER
  6. systemctl --user daemon-reexec

Then:

systemctl --user daemon-reload
systemctl --user start foo
journalctl --user-unit foo

Service file

[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

[Install]
# start service on system start-up
WantedBy=default.target

Bibliography

See also