TT Lab
Blog Get started
Learn Learning paths Courses

RHEL-Family Administration

Writing a systemd Unit File

Continue in TT Lab

Goal

You write a systemd unit file from scratch, make a timer pair, and build a unit verification script yourself. In the final step, under a real systemd, you work out per service why "the services are not running after a reboot" and fix it.

Why it matters

The most important line in a unit file is Type=. If it is Type=simple but the process daemonizes, systemd sees the parent dying as the service ending and treats it as a failure. Conversely, if it is Type=forking but the process runs in the foreground, systemd waits for the parent to finish and then kills it on a timeout — the typical cause of "the start hangs for a long while and then fails".

And without an [Install] section, systemctl enable does nothing, so automatic start at boot does not happen. Failures at boot usually go unnoticed until a reboot: one executable path, one missing env file, one line of ordering where units wait for each other surfaces only after a dawn reboot. For a service that is off without even a failure marker, you must look for the cause not in that unit but in systemd's own journal.

This lab runs on an AlmaLinux 9 virtual machine. Because systemd really runs as PID 1, after writing a unit file you can start it right away. It takes about 30 seconds to start the first time.

Steps

  1. Create /etc/systemd/system/labhub-api.service and put in the three sections [Unit], [Service], and [Install]. Also create the /root/unit working directory.
  2. In [Unit], write a description (Description) and a documentation address (Documentation), and set both the ordering and a weak dependency so that it starts after network-online.target.
  3. Fill in [Service]: type notify, the command /usr/local/bin/labhub-api --config /etc/labhub/api.yaml (an absolute path), account and group labhub, working directory /opt/labhub, and notify access all so that readiness notifications from child processes are accepted too.
  4. Restart policy: restart only on failure at 5-second intervals, and give up if it exceeds 5 times within 300 seconds. Put the two start-count limits in [Unit].
  5. Security directives: no privilege escalation, a read-only system (strict), hidden home, a private /tmp, and only /var/lib/labhub and /var/log/labhub as write exceptions.
  6. Put WantedBy=multi-user.target in [Install], and make the symlink /etc/systemd/system/multi-user.target.wants/labhub-api.service that systemctl enable would create point to the original unit.
  7. Create a timer pair. /etc/systemd/system/labhub-backup.service (Type=oneshot, an absolute path for ExecStart) and /etc/systemd/system/labhub-backup.timer (in [Timer], OnCalendar=*-*-* 02:30:00, Persistent=true, and Unit=labhub-backup.service, and in [Install], WantedBy=timers.target).
  8. Write /root/unit/lint.sh. It must take the unit file path as its first argument, check the following three rules, and end with exit code 0 if there are no violations and a nonzero value if there are.
    • Rule 1: all three sections [Unit], [Service], and [Install] must be present
    • Rule 2: the ExecStart value must be an absolute path (starting with /)
    • Rule 3: if Type=forking, PIDFile= must be present The grader runs it against both your labhub-api.service (it must pass) and /opt/fixtures/unit/bad-sample.service (it must fail).
  9. Incident: raise incident rh-unit-boot, work out per service why four acme services that should come up together at boot are not running, and fix the units. The report is /root/incident/rh-unit-boot/report.txt.

Notes

Three-section skeleton

Create /etc/systemd/system/labhub-api.service and put in the three sections [Unit], [Service], and [Install]. Also create the /root/unit working directory.

You need three section names wrapped in square brackets. There is a convention for the order too.

Filling in the [Unit] section

In [Unit], write a description (Description) and a documentation address (Documentation), and set both the ordering and a weak dependency so that it starts after the network is actually up (network-online.target) (two directives with the same target as the value).

Direction: [Unit] decides "who it lives with, and in what order". The directive that only sets ordering and the directive that also pulls the other unit up do different jobs, and if you use only one, they start at the same time or the other one does not come up. Tools: the ordering and dependency directives in the systemd.unit manual. Concretely: network.target only means "the stack has started coming up"; what means after addresses are attached is network-online.target.

[Service] execution settings

Fill in [Service]. The type is notify, which waits until the program sends a readiness notification; the command is /usr/local/bin/labhub-api --config /etc/labhub/api.yaml (an absolute path); the account and group are labhub; and the working directory is /opt/labhub. The lab program is a shell script, so a child process sends the readiness notification; set notify access to all so that notifications from processes other than the main PID are accepted too. With the default (main), systemd discards that notification and waits until it ends with a timeout, while there seems to be nothing wrong with the unit file.

Direction: the most important line in [Service] is the type, because it decides when systemd considers startup finished. Tools: Type, NotifyAccess, ExecStart, User, Group, and WorkingDirectory in the systemd.service manual. Concretely: the command runs directly without going through a shell, so it must be an absolute path, and pipes and redirection do not work.

Restart policy

Add a restart policy. Restart only on failure (on-failure) at 5-second intervals, and give up if it exceeds 5 times within 300 seconds. Put the restart mode and interval in [Service], and the two start-count limits (StartLimitIntervalSec, StartLimitBurst) in [Unit]: these two moved to [Unit] in systemd 230, and if you write them in [Service], only Unknown key name is left and they are silently ignored, so no rate limit applies.

Direction: a restart policy is a set of four lines: when to restart, how long to rest before restarting, and how many times to allow within how long. Without a limit, one dying service eats away the CPU and the journal. Tools: Restart and RestartSec in systemd.service, the StartLimit directives in systemd.unit. Concretely: always revives it even after a normal exit. An interval of 0 becomes a loop that starts and dies dozens of times per second.

Security hardening

Add security directives to [Service]. No privilege escalation (NoNewPrivileges true), the whole system read-only (ProtectSystem strict), hidden home (ProtectHome true), a private /tmp (PrivateTmp true), and reopen as write exceptions (ReadWritePaths) only the two places the service actually has to write, /var/lib/labhub and /var/log/labhub.

Direction: security directives are mechanisms that turn on the kernel's mount namespaces and no_new_privs per unit. Making the whole system read-only also blocks the paths the service was writing to. Tools: the protection directives in the systemd.exec manual. Concretely: "the service stops starting once strict is on" is almost always a missing write exception; write both exceptions on one line separated by a space.

[Install] and the result of enable

Put WantedBy=multi-user.target in [Install], and create by hand the symlink that systemctl enable would create. The path is /etc/systemd/system/multi-user.target.wants/labhub-api.service and it must point to the original unit.

Direction: [Install] is the only place enable reads, and all enable actually does is put one symlink in the target's .wants directory. Tools: creating a directory and a symbolic link, and checking the enable result (is-enabled). Concretely: it must be a link, not a copy, so that edits to the original are reflected as they are. Compare once whether what you made by hand is the same as what enable makes.

Writing a timer pair

Create a timer pair. /etc/systemd/system/labhub-backup.service (Type=oneshot, an absolute path for ExecStart) and /etc/systemd/system/labhub-backup.timer (in [Timer], OnCalendar=*-*-* 02:30:00, Persistent=true, and Unit=labhub-backup.service, and in [Install], WantedBy=timers.target).

Direction: a timer is systemd's version of cron. Write the job to run in the .service and the time in the .timer, separating "what" from "when". Tools: the systemd.timer manual, and systemd-analyze calendar to check a time expression. Concretely: check the service type for a job that runs once and ends, the directive that catches up after boot on runs missed while the machine was off, and the target the timer hooks onto (timers.target).

Unit verification script

Write /root/unit/lint.sh. It must take the unit file path as its first argument, check the following three rules, and end with exit code 0 if there are no violations and a nonzero value if there are.

Direction: most accidents can be caught by looking only at the file, without starting the unit. The third of the three rules is conditional, so checking it unconditionally makes even a good unit fail. Tools: line-by-line regular expressions (anchor the whole line for section headers), exit codes. Concretely: the grader runs it on three cases (a good unit, the bad sample, and a forking case) to see whether the results differ, and then actually starts labhub-api.

Incident: after a reboot, four of the five acme services are not running

Running incident rh-unit-boot makes acme-stack.target bring up five services (acme-report, acme-sync, acme-queue, acme-web, acme-cache) as it would at boot, but four of them are not running (read the ticket first). Classify each of acme-report, acme-sync, acme-queue, and acme-web as one of envfile-missing (the EnvironmentFile does not exist), exec-missing (there is no executable at the ExecStart path), ordering-cycle (units wait for each other in their ordering), type-mismatch (the Type does not match how the program runs), or user-missing (the User account does not exist), and fix the units so that all five come up when acme-stack.target is brought up again. The programs in /opt/acme/bin are managed by the deployment tool, so you must not modify them or put new ones there; acme-sync's settings go in an env file, and acme-web must still start after acme-cache. The grader stops all five and brings the target up again to check. In /root/incident/rh-unit-boot/report.txt, write four lines <서비스>: <코드> (service: code) and evidence: <관찰한 출력 한 줄> (one line of output you observed).

Direction: even though "it is not running" is the same, the Result and exit status systemd left behind differ per service. And for one that is inactive without even a failure marker, you must look not at that unit's log but at the lines systemd itself left. Tools: unit status (Result, status=), property view (show -p), per-unit journals and systemd's journal, unit file checks (systemd-analyze verify), and how the program actually runs (in the foreground?). Concretely: 203/EXEC, resources, and timeout are failures at different stages. An ordering loop becomes visible when you put the After= of two units side by side. After fixing a unit, you must have systemd reread it.