Skip to content

Services with systemd

systemd runs your services, your logs, your timers, your mounts, your DNS resolver, and if you squint, your life. People have opinions about it. I used to. Then I had to write init scripts by hand for a while, and now I keep my opinions to myself.

Terminal window
systemctl status nginx # is it running, and the last few log lines. Start here. Always.
systemctl start nginx
systemctl stop nginx
systemctl restart nginx # stop + start. Drops connections.
systemctl reload nginx # re-read config without restarting, IF the service supports it
systemctl enable nginx # start at boot (does NOT start it now)
systemctl enable --now nginx # start at boot AND now. This is the one you want.
systemctl disable --now nginx
systemctl is-enabled nginx
systemctl --failed # everything that's broken. Check after every reboot.

Your app needs to run forever and come back when it dies. Do not use screen. Do not use nohup ... &. Do not put it in rc.local. I’ve inherited all three. Write a unit file.

/etc/systemd/system/myapp.service:

[Unit]
Description=My App (the one that pays the bills)
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
EnvironmentFile=/etc/myapp/env
ExecStart=/opt/myapp/bin/myapp --port 8080
Restart=on-failure
RestartSec=5
# Hardening. Costs you nothing. Saves you a lot.
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target

Then:

Terminal window
sudo systemctl daemon-reload # systemd will NOT notice your edit until you do this
sudo systemctl enable --now myapp
systemctl status myapp

Things worth knowing:

  • ExecStart needs an absolute path. No ~, no relying on $PATH, no shell features. If you want pipes or &&, use ExecStart=/bin/sh -c '...', and then ask yourself why.
  • Type=simple is for programs that stay in the foreground. If your program forks itself into the background, systemd thinks it died immediately. Either tell the program not to daemonize (better) or use Type=forking (worse).
  • Restart=on-failure restarts on crashes. Restart=always also restarts on clean exits. Pick deliberately.
  • Don’t run as root. Create a user: sudo useradd --system --no-create-home --shell /usr/sbin/nologin myapp.
  • EnvironmentFile is KEY=value lines. No export. Quoting rules are subtly different from a shell’s. Keep values boring.

If a service crashes too many times too fast, systemd gives up. Status will say something like start request repeated too quickly. Fix the actual problem, then:

Terminal window
sudo systemctl reset-failed myapp
sudo systemctl start myapp

Changing a packaged service without editing its file

Section titled “Changing a packaged service without editing its file”

Never edit files under /lib/systemd/system/ (or /usr/lib/systemd/system/). The package manager will overwrite them on the next update and you’ll spend a day figuring out why your change “un-happened.”

Use a drop-in instead:

Terminal window
sudo systemctl edit nginx

That opens an editor for /etc/systemd/system/nginx.service.d/override.conf. Put only the bits you’re changing:

[Service]
LimitNOFILE=65535

One trap: some settings are lists, and adding a line appends. To replace ExecStart, you have to clear it first:

[Service]
ExecStart=
ExecStart=/usr/sbin/nginx -g 'daemon off;'

Yes, an empty assignment to clear it. No, I didn’t design it. systemctl cat nginx shows the final merged result, which is the only version you should trust.

Terminal window
journalctl -u myapp # all logs for a unit
journalctl -u myapp -f # follow, like tail -f
journalctl -u myapp -n 100 --no-pager
journalctl -u myapp --since "1 hour ago"
journalctl -u myapp -b # since the current boot
journalctl -b -1 -p err # errors from the PREVIOUS boot. Gold after a surprise reboot.
journalctl --disk-usage
sudo journalctl --vacuum-time=14d # when /var/log/journal ate the disk

If journalctl -b -1 says there’s no previous boot, the journal isn’t persistent. Fix that now, before you need it:

Terminal window
sudo mkdir -p /var/log/journal
sudo systemctl restart systemd-journald

Timers (cron, but you can see what happened)

Section titled “Timers (cron, but you can see what happened)”

Cron is fine. Cron is also where jobs go to fail silently for six months. systemd timers log to the journal and show up in systemctl list-timers, which is enough for me.

/etc/systemd/system/backup.service:

[Unit]
Description=Nightly backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

/etc/systemd/system/backup.timer:

[Unit]
Description=Run backup nightly
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
RandomizedDelaySec=10m
[Install]
WantedBy=timers.target
Terminal window
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer # enable the TIMER, not the service
systemctl list-timers
sudo systemctl start backup.service # run it now to check it actually works

Persistent=true means if the box was off at 3 AM, it runs at next boot. systemd-analyze calendar "*-*-* 03:00:00" tells you when a schedule will next fire, so you don’t have to reason about it at 2 AM.

  1. systemctl status myapp. Read the whole thing, including the log lines at the bottom.
  2. journalctl -u myapp -n 50 --no-pager
  3. systemd-analyze verify /etc/systemd/system/myapp.service catches typos.
  4. Run the ExecStart command by hand as the service user: sudo -u myapp /opt/myapp/bin/myapp --port 8080. Ninety percent of the time it’s permissions, a missing env var, or a relative path.
  5. Did you daemon-reload? Do it again anyway. It’s free.