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.
The commands
Section titled “The commands”systemctl status nginx # is it running, and the last few log lines. Start here. Always.systemctl start nginxsystemctl stop nginxsystemctl restart nginx # stop + start. Drops connections.systemctl reload nginx # re-read config without restarting, IF the service supports itsystemctl 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 nginxsystemctl is-enabled nginxsystemctl --failed # everything that's broken. Check after every reboot.Writing your own service
Section titled “Writing your own service”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.targetAfter=network-online.target
[Service]Type=simpleUser=myappGroup=myappWorkingDirectory=/opt/myappEnvironmentFile=/etc/myapp/envExecStart=/opt/myapp/bin/myapp --port 8080Restart=on-failureRestartSec=5
# Hardening. Costs you nothing. Saves you a lot.NoNewPrivileges=trueProtectSystem=fullProtectHome=truePrivateTmp=true
[Install]WantedBy=multi-user.targetThen:
sudo systemctl daemon-reload # systemd will NOT notice your edit until you do thissudo systemctl enable --now myappsystemctl status myappThings worth knowing:
ExecStartneeds an absolute path. No~, no relying on$PATH, no shell features. If you want pipes or&&, useExecStart=/bin/sh -c '...', and then ask yourself why.Type=simpleis 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 useType=forking(worse).Restart=on-failurerestarts on crashes.Restart=alwaysalso 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. EnvironmentFileisKEY=valuelines. Noexport. Quoting rules are subtly different from a shell’s. Keep values boring.
Restart loops
Section titled “Restart loops”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:
sudo systemctl reset-failed myappsudo systemctl start myappChanging 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:
sudo systemctl edit nginxThat opens an editor for /etc/systemd/system/nginx.service.d/override.conf. Put only the bits you’re changing:
[Service]LimitNOFILE=65535One 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.
Logs: journalctl
Section titled “Logs: journalctl”journalctl -u myapp # all logs for a unitjournalctl -u myapp -f # follow, like tail -fjournalctl -u myapp -n 100 --no-pagerjournalctl -u myapp --since "1 hour ago"journalctl -u myapp -b # since the current bootjournalctl -b -1 -p err # errors from the PREVIOUS boot. Gold after a surprise reboot.journalctl --disk-usagesudo journalctl --vacuum-time=14d # when /var/log/journal ate the diskIf journalctl -b -1 says there’s no previous boot, the journal isn’t persistent. Fix that now, before you need it:
sudo mkdir -p /var/log/journalsudo systemctl restart systemd-journaldTimers (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=oneshotExecStart=/usr/local/bin/backup.sh/etc/systemd/system/backup.timer:
[Unit]Description=Run backup nightly
[Timer]OnCalendar=*-*-* 03:00:00Persistent=trueRandomizedDelaySec=10m
[Install]WantedBy=timers.targetsudo systemctl daemon-reloadsudo systemctl enable --now backup.timer # enable the TIMER, not the servicesystemctl list-timerssudo systemctl start backup.service # run it now to check it actually worksPersistent=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.
Debugging a unit that won’t start
Section titled “Debugging a unit that won’t start”systemctl status myapp. Read the whole thing, including the log lines at the bottom.journalctl -u myapp -n 50 --no-pagersystemd-analyze verify /etc/systemd/system/myapp.servicecatches typos.- Run the
ExecStartcommand 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. - Did you
daemon-reload? Do it again anyway. It’s free.