Linux Labs

Packages, services, and logs / Stage 6 of 13

Services under systemd

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 7 · theory · 5 min

The unit file

Whether to bring a service back after a crash, systemd reads in the service's description. This step covers where that description lives and which of its lines matter most.

systemd learns how to start a service from its unit file. The path to it is on the Loaded line of the systemctl status summary, and systemctl cat prints the whole file. This is what systemctl cat cron prints on the training machine:

ini
# /usr/lib/systemd/system/cron.service
[Unit]
Description=Regular background program processing daemon
Documentation=man:cron(8)
After=remote-fs.target nss-user-lookup.target

[Service]
EnvironmentFile=-/etc/default/cron
ExecStart=/usr/sbin/cron -f -P $EXTRA_OPTS
IgnoreSIGPIPE=false
KillMode=process
Restart=on-failure
SyslogFacility=cron

[Install]
WantedBy=multi-user.target

The cron package installed this file: dpkg -S /usr/lib/systemd/system/cron.service from the packages module prints cron: /usr/lib/systemd/system/cron.service.

The file is split into sections in square brackets, each holding key=value lines. Two lines of the [Service] section explain what you saw:

  • ExecStart — which program to start. For cron it is /usr/sbin/cron -f -P.
  • Restart — whether to start the service again once its process has ended. on-failure means "after a failure": the process exited with a non-zero code, was killed by a signal or ran out of time.

Lines starting with # are comments, and systemd skips them. The nginx file is long, so it is printed with --no-pager; otherwise systemctl cat opens it in a pager:

bash
systemctl cat nginx --no-pager

The nginx file has no Restart line. Then the default applies, no: after a crash systemd does not start the service again, and it stays failed.

Check yourself 1 question

A service's unit has Restart=on-failure. Its program finished its work and exited with code 0. What does systemd do?

  • on-failure fires after a failure: a non-zero code, a signal or a timeout. Code 0 means the program finished normally.

  • Code 0 is not a failure: there is nothing to mark as failed, and on-failure does not fire.

  • Restart has nothing to do with autostart: systemctl is-enabled prints the same as before the program exited.

on-failure restarts the service after a failure: a non-zero exit code, a signal or a timeout. A program that exits with code 0 finished normally, and the service stays inactive.

Key points

  • A service is described by its unit file: its path is on the Loaded line, and systemctl cat prints the whole file.
  • ExecStart is the service's program, Restart says whether to start it again; without Restart a crashed service stays failed.
Ubuntu 24.04
Loading…