DEVOPS, SRE AND CLOUD · PART 1 · LINUX, FROM THE INSIDE · SERVICES · 16 OF 187

systemd Explained: Units, Services and journald Logs

How to run your own app as a proper Linux service: a systemd unit file for ShopRung line by line (user, working directory, ExecStart, Restart=on-failure), systemctl start, enable and status, dependencies and targets, drop-in overrides, journalctl to read logs by service, boot and priority, and systemd-analyze verify, which caught a wrong ExecStart path in our unit before it ever ran.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Unit files
  • verify
  • daemon-reload
  • enable --now
  • status
  • Restart=on-failure
  • journalctl -u
  • drop-ins

Notes

Unit files

systemd manages units. A service unit runs a program, a socket unit starts something when a connection arrives, a timer unit runs things on a schedule, a mount unit mounts a filesystem, and a target groups other units. Units are small text files. Yours go in etc systemd system; the ones installed by packages live in lib systemd system, and yours win if the names match.

Kinds of units
  • .service a program to run
  • .socket start on connection
  • .timer run on a schedule
  • .mount a filesystem
  • .target a group of units
  • yours: /etc/systemd/system/ packages: /lib/systemd/system/

ShopRung's unit

Here is ShopRung's unit. The unit section gives a description and says start after the network is up. The service section says run as the user shoprung, never root, in the folder opt shoprung, with this exact command and this environment variable. Restart on failure, after two seconds. The install section says this service belongs to multi user target, so enabling it makes it start at boot. Thirteen lines, and the app is now a real service.

shoprung.service
[Unit] Description=ShopRung
After=network-online.target
Wants=network-online.target
[Service] User=shoprung
WorkingDirectory=/opt/shoprung
ExecStart=/usr/bin/node src/server.js
Environment=PORT=8080
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target

Verify first

Before starting it, check it. systemd analyze verify reads the unit and reports problems, and on our machine it found one: the command slash usr slash bin slash node did not exist, because Node was installed in opt node twenty two. ExecStart needs a full, real path; systemd does not use your shell's PATH. which node gives the right one. Thirty seconds of verify saves a confusing failed start later.

Our run
$ systemd-analyze verify
    shoprung.service
shoprung.service: Command
  /usr/bin/node is not
  executable: No such file
  or directory

on that machine node lived in
  /opt/node22/bin/node
fix: ExecStart with the real
  path (which node)

systemctl

After creating or changing a unit, run daemon reload so systemd reads it again. Start runs it now. Enable makes it start at boot; enable with now does both. Status shows whether it is active, its main process ID, memory, and the last few log lines, which is the first thing to check when a service misbehaves. Restart restarts it, and list units with failed shows every service that has crashed.

The commands
$ sudo systemctl daemon-reload
$ sudo systemctl start shoprung
$ sudo systemctl enable shoprung
  (or enable --now: both)
$ systemctl status shoprung
  ● Active: active (running)
  Main PID, memory, last logs
$ sudo systemctl restart shoprung
$ systemctl list-units --failed

Restarts

With restart on failure, if ShopRung exits with an error or is killed, systemd waits two seconds and starts it again. If it crashes too many times in a short window, systemd gives up and marks it failed, so a broken app does not spin forever. When you stop a service, systemd sends SIGTERM, waits up to ninety seconds by default, then SIGKILL, exactly as in the last episode. Remember that automatic restarts hide crashes, so always read the logs.

When the app crashes
  • exit code ≠ 0 or killed → wait RestartSec, start again
  • too many restarts in a short window → systemd gives up (StartLimitBurst, Interval)
  • stop: SIGTERM, wait 90 s (TimeoutStopSec), then KILL
  • a restart loop hides the bug: read the logs

journald

Anything a service prints to standard output or error is captured by journald, tagged with the unit name, and indexed. journalctl minus u shoprung shows ShopRung's logs; minus f follows them live. Since ten minutes ago narrows the time. Minus b with priority error shows only errors since the last boot. And disk usage tells you how much space the journal uses, which you can cap in journald's config.

journalctl
$ journalctl -u shoprung
$ journalctl -u shoprung -f
  follow, like tail -f
$ journalctl -u shoprung
    --since "10 min ago"
$ journalctl -b -p err
  errors since this boot
$ journalctl --disk-usage

Overrides

To change a service that came with a package, never edit its file, because updates overwrite it. systemctl edit creates a drop-in override file, where you add only the lines you want to change, like a higher open-files limit or a different restart policy. systemctl cat shows the original file and every override together, so you can see exactly what systemd will run.

Drop-ins
$ sudo systemctl edit nginx
  creates /etc/systemd/system/
  nginx.service.d/override.conf
[Service]
LimitNOFILE=65536
Restart=always

$ systemctl cat nginx
  shows the file + overrides

Hardening for free

systemd can also sandbox a service with a few lines. No new privileges, protect system strict and protect home make most of the disk read-only or invisible to it. Private tmp gives it its own temporary folder, and read write paths opens just the folders it needs. Memory max and CPU quota set resource limits using cgroups, the same mechanism containers use. systemd analyze security scores how exposed a service is.

Useful [Service] options
  • NoNewPrivileges=true
  • ProtectSystem=strict
  • ProtectHome=true
  • PrivateTmp=true
  • ReadWritePaths=/var/lib/shoprung
  • MemoryMax=512M (cgroup limit)
  • CPUQuota=50%
  • $ systemd-analyze security shoprung

Common mistakes

Mistakes. Changing a unit and forgetting daemon reload. Starting a service but never enabling it, so it vanishes after reboot. A relative or wrong ExecStart path. Running the service as root. Editing package unit files instead of using overrides. And a restart policy that hides a crash loop because nobody reads the journal.

Avoid these
  • forgetting daemon-reload
  • start but never enable
  • relative ExecStart or relying on your shell's PATH
  • running services as root
  • editing /lib/systemd files
  • Restart=always hiding a crash loop

Say it like this

In the interview: I write a unit file in etc systemd system with a dedicated user, a working directory, the full ExecStart path, restart on failure and wanted by multi user target. I check it with systemd analyze verify, run daemon reload, then enable with now, and check status. Logs come from journalctl minus u, and I change packaged services with drop-in overrides, adding sandboxing options and limits.

In the interview
  • "I write a unit in /etc/systemd/ system: its own user, working
  • directory, full ExecStart path, Restart=on-failure, WantedBy= multi-user.target. Verify, daemon- reload, enable --now, check
  • status, and read logs with journalctl -u."

Interview questions

Q1How do you run an application as a systemd service?

Create /etc/systemd/system/<name>.service with User, WorkingDirectory, a full ExecStart path, Restart=on-failure and WantedBy=multi-user.target; then systemctl daemon-reload and systemctl enable --now <name>.

Q2What is the difference between start and enable?

start runs the service now; enable makes it start at boot (by linking it into a target). enable --now does both.

Q3How do you read a service's logs?

journalctl -u <unit>, with -f to follow, --since to limit time, -b for this boot and -p err for errors only.

Q4How do you change a packaged service safely?

systemctl edit <unit> creates a drop-in override in /etc/systemd/system/<unit>.d/; systemctl cat shows the merged result.

Q5Why does systemd say the command is not executable?

ExecStart must be an absolute path that exists; systemd does not use your shell PATH. Check with which and systemd-analyze verify.

Q6What does Restart=on-failure do?

Restarts the service after a non-zero exit, a signal kill or a timeout, waiting RestartSec, within StartLimitBurst/StartLimitIntervalSec limits.

Q7How do you find failed services?

systemctl --failed (or list-units --failed), then systemctl status and journalctl -u for each.

Q8How can systemd limit a service's resources?

With cgroup settings like MemoryMax and CPUQuota, plus sandboxing such as ProtectSystem, PrivateTmp and NoNewPrivileges.