Running services with systemd

Intermediate · 14 min

Keep a program running across crashes, logouts and reboots: what systemd does as PID 1, how to read and write a unit file, and where its logs go.

Before thisThe Linux server from an operator's seat

tutoriaLinux · 14 min

Running services with systemd

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by tutoriaLinuxReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • systemd is the first process a modern Linux system starts. It starts services at boot, restarts them when they crash, and records their output in the journal.
  • A unit file describes one thing systemd manages. A service unit says what to run, as which user, when to restart it, and which target it belongs to.
  • Packages install units under /usr/lib/systemd/system. Your own units and overrides go in /etc/systemd/system, which wins.
  • After changing a unit file, run systemctl daemon-reload so systemd reads it again, then restart the service.
  • enable makes a service start at boot. start runs it now. enable --now does both.

The problem: who restarts it?

You start your API on a server with nohup ./notes-api &, log out, and it keeps running. That is the trick from surviving logout. Then three things happen over a month. The process crashes on a bad request and nobody notices for an hour. The server reboots for a kernel update and the API never comes back. Someone asks for yesterday’s error output, and it went to a file that filled the disk, or to nowhere.

What you want is a supervisor: something that starts the program at boot, notices when it dies, starts it again, keeps its output, and stops it cleanly on shutdown. On almost every current Linux distribution that supervisor is systemd.

What systemd is

When the kernel finishes booting it starts exactly one program, process ID 1, and everything else descends from it. On Debian, Ubuntu, Fedora, RHEL and most others, PID 1 is systemd. It reads a set of unit files, works out their dependencies, and starts things in order.

A unit is one thing systemd manages. The kinds you meet first:

  • service: a program to run, like nginx.service.
  • timer: a schedule that starts a service, a more capable replacement for cron.
  • target: a named group of units, like multi-user.target, which roughly means “the system is up and ready for services”.

systemd also places each service in its own control group, the kernel feature that tracks every process a service starts and can limit its CPU and memory. That is why systemctl stop can reliably kill a service and all its children. You will meet control groups again in what a container really is.

Reading a real unit file

I did not have a Linux machine with systemd to work on. What I could do was pull the official nginx image from Docker Hub, unpack its layers, and read the unit file that the nginx.org Debian package installs. This is it, unchanged:

[Unit]
Description=nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
Environment="CONFFILE=/etc/nginx/nginx.conf"
Environment="cmdopts="
EnvironmentFile=-/etc/default/nginx
ExecStart=/usr/sbin/nginx -c ${CONFFILE} $cmdopts
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /run/nginx.pid)"

[Install]
WantedBy=multi-user.target

It lives at /usr/lib/systemd/system/nginx.service, the directory packages own. Section by section:

  • [Unit] is ordering. After= and Wants= say “start me once the network is up”, so nginx does not try to bind before an address exists.
  • [Service] is how to run it. Type=forking means nginx starts, forks a background master process and the launcher exits, so systemd follows the PID written to /run/nginx.pid. ExecReload sends HUP, which nginx treats as “reread your config without dropping connections”. The signals lesson explains why HUP and TERM mean different things.
  • [Install] says which target pulls this unit in when it is enabled. WantedBy=multi-user.target is the standard “start at boot”.

The - in EnvironmentFile=-/etc/default/nginx means “if this file is missing, carry on”.

The same image’s Debian base also ships a timer, apt-daily.timer, with OnCalendar=*-*-* 6,18:00 and RandomizedDelaySec=12h. That random delay is something cron cannot do, and it stops thousands of machines from hitting the package mirrors at the same second.

Writing your own

Here is a unit for the notes API, written from the systemd.service and systemd.exec man pages. I could not load or run it, since this Mac has no systemd.

# /etc/systemd/system/notes-api.service
[Unit]
Description=Notes API
After=network-online.target
Wants=network-online.target

[Service]
Type=exec
User=notes
WorkingDirectory=/srv/notes-api
EnvironmentFile=/etc/notes-api/env
ExecStart=/srv/notes-api/bin/notes-api --port 8080
Restart=on-failure
RestartSec=2
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/notes-api

[Install]
WantedBy=multi-user.target

The choices that matter: it runs as an unprivileged notes user, not root. Type=exec makes systemctl start fail visibly if the binary cannot be executed, where Type=simple would report success. Restart=on-failure brings it back after a crash but not after a clean stop. The last three lines are cheap hardening: ProtectSystem=strict mounts the filesystem read-only for this service except the paths you list.

Then, on the server:

sudo systemctl daemon-reload            # reread unit files
sudo systemctl enable --now notes-api   # start at boot, and start now
systemctl status notes-api              # state, PID, last log lines
journalctl -u notes-api -f              # follow its output
sudo systemctl edit nginx               # override a packaged unit safely

Anything your program writes to stdout or stderr lands in the journal, indexed by unit, so journalctl -u notes-api --since "1 hour ago" replaces hunting for log files. For a packaged unit, never edit the file under /usr/lib. systemctl edit creates a drop-in under /etc/systemd/system/nginx.service.d/, which survives upgrades and wins over the package’s copy.

About the video

“systemd on Linux 1: Intro and Unit Files” is from tutoriaLinux (Dave Cohen), published June 2021, 13 minutes 48 seconds. Its chapters go from what init is and the older SysV init, through unit types and unit file locations, to writing a simple unit file, daemon-reload, and a closer look at an nginx unit file. That matches this lesson’s path almost exactly. systemd’s basics have not changed since 2021. The video does not cover journalctl or hardening options, so the Akamai video in deeper covers the journal. English was judged from the title, description, channel and its English auto-caption track.

Where this fits

A service now survives crashes and reboots. Next, how you and your tools get onto the server at all, safely: SSH keys, bastions and remote access.

Check yourself

  1. 01Your app runs fine under nohup but is gone after the server reboots. What does a systemd unit add?

    An [Install] section with WantedBy=multi-user.target, enabled with systemctl enable, makes systemd start it at every boot. Restart=on-failure also brings it back after a crash.

  2. 02You edited /etc/systemd/system/notes-api.service, restarted the service, and nothing changed. What did you forget?

    systemctl daemon-reload. systemd caches unit files and only rereads them on a reload.

  3. 03Where do you look for the output of a service that keeps crashing?

    journalctl -u notes-api, adding -f to follow it live or -b to limit it to the current boot. systemctl status also shows the last few lines.

  4. 04Why change a packaged unit with systemctl edit rather than editing the file under /usr/lib?

    systemctl edit writes a drop-in under /etc/systemd/system that survives package upgrades. A package update would overwrite edits made to its own file.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark