8.3. Creating and Adapting Services
This section builds the handbook-heartbeat service that Section 8.2
operated: a system account, a long-running program, a unit file, and the
directives that make the combination survive reboots, reloads, and crashes.
8.3.1. Writing a Service for a Long-Running Application
The heartbeat is a small Python program that prints a timestamped line,
writes a state file, and treats SIGHUP as "re-read configuration". It
uses the python3-systemd package for the notify calls, so install that
first (apt install python3-systemd). The service needs a dedicated
system account rather than root; as root on client1, create a group and a
system user whose home directory is the state directory:
# groupadd --system handbook-app
# useradd --system --gid handbook-app --home-dir /var/lib/handbook-heartbeat --no-create-home --shell /usr/sbin/nologin handbook-app
Both commands are silent. --system allocates the account from the low UID
range intended for services, and nologin prevents anyone from logging in
as it; the account-selection criteria are the ones from
Chapter 5. Create the program directory:
# install -d -m 755 /opt/handbook-heartbeat
Save this as /opt/handbook-heartbeat/heartbeat.py:
#!/usr/bin/env python3
import os
import pathlib
import signal
import time
try:
from systemd import daemon as sd
except ImportError:
sd = None
ENV_FILE = os.environ.get("HEARTBEAT_ENV_FILE",
"/etc/handbook-heartbeat/heartbeat.env")
STATE_FILE = pathlib.Path(os.environ.get("HEARTBEAT_STATE",
"heartbeat.state"))
stopping = False
def read_interval():
value = os.environ.get("HEARTBEAT_INTERVAL", "5")
try:
with open(ENV_FILE, encoding="utf-8") as handle:
for line in handle:
key, _, raw = line.partition("=")
if key.strip() == "HEARTBEAT_INTERVAL":
value = raw.strip().strip('"')
except OSError:
pass
return float(value)
interval = read_interval()
def reload_config(signum, frame):
global interval
interval = read_interval()
print(f"reloaded interval={interval:g}s", flush=True)
def stop(signum, frame):
global stopping
stopping = True
signal.signal(signal.SIGHUP, reload_config)
signal.signal(signal.SIGTERM, stop)
print(f"starting pid={os.getpid()} interval={interval:g}s", flush=True)
if sd is not None:
sd.notify("STATUS=initialising")
time.sleep(1)
if sd is not None:
sd.notify("READY=1\nSTATUS=heartbeat running")
while not stopping:
print(f"heartbeat {time.strftime('%Y-%m-%dT%H:%M:%S%z')}", flush=True)
STATE_FILE.write_text(f"{time.time():.0f}\n")
time.sleep(interval)
if sd is not None:
sd.notify("STOPPING=1")
print("stopping", flush=True)
Make it executable:
# chmod 755 /opt/handbook-heartbeat/heartbeat.py
The application takes one setting - its tick interval - from an environment file. As root, create the directory with the service group able to read it, and save the file:
# install -d -m 750 -o root -g handbook-app /etc/handbook-heartbeat
Contents of /etc/handbook-heartbeat/heartbeat.env:
HEARTBEAT_INTERVAL=5
# chown root:handbook-app /etc/handbook-heartbeat/heartbeat.env
# chmod 640 /etc/handbook-heartbeat/heartbeat.env
Both commands are silent. The result is a file owned by root but readable by the service group - the application can read its configuration but cannot modify it, and no other account can read it at all. Section 8.3.2 verifies that identity and exercises the file's one setting.
The sd.notify("READY=1") call is what makes the service verifiably
ready, as the service types below explain. Now the unit; save it as
/usr/local/lib/systemd/system/handbook-heartbeat.service, the search-path
layer for locally installed software:
[Unit]
Description=Handbook heartbeat service
Documentation=file:/opt/handbook-heartbeat/heartbeat.py
After=network.target
StartLimitIntervalSec=30
StartLimitBurst=3
[Service]
Type=notify
User=handbook-app
Group=handbook-app
WorkingDirectory=/var/lib/handbook-heartbeat
EnvironmentFile=/etc/handbook-heartbeat/heartbeat.env
Environment=HEARTBEAT_ENV_FILE=/etc/handbook-heartbeat/heartbeat.env
ExecStart=/opt/handbook-heartbeat/heartbeat.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=2
TimeoutStartSec=10
StateDirectory=handbook-heartbeat
StateDirectoryMode=0750
LogsDirectory=handbook-heartbeat
StandardOutput=journal
StandardError=journal
SyslogIdentifier=handbook-heartbeat
[Install]
WantedBy=multi-user.target
Read it top to bottom. [Unit] describes relationships: run after the
network is up, and - StartLimitIntervalSec with StartLimitBurst - give
up if the unit is started more than three times in thirty seconds
(Section 8.3.4 breaks that deliberately). [Service] says who runs it
(User=/Group=), where (WorkingDirectory=), what to run
(ExecStart=), how to reload (ExecReload=, using the $MAINPID
variable systemd fills in), when to restart, and where stdout and stderr
go - here the journal, under the identifier handbook-heartbeat.
StateDirectory= and LogsDirectory= make systemd create
/var/lib/handbook-heartbeat and /var/log/handbook-heartbeat with the
right ownership at start time. [Install] names the target whose .wants
directory enable will link into.
The one choice worth dwelling on is Type=:
| Type | systemd treats the unit as started when... |
Fits |
|---|---|---|
simple |
the process has been forked and exec'd | programs that are ready as soon as they run |
exec |
the exec has succeeded | like simple, but a missing binary fails the start job |
forking |
the initial process exits | classic daemons that fork into the background |
notify |
the process sends READY=1 |
programs with a warm-up phase before they are usable |
oneshot |
the single ExecStart command exits |
batch jobs; RemainAfterExit=yes keeps state "active" afterwards |
notify is the honest choice for anything that needs preparation: a start
job only succeeds once the application itself says it is ready, and the
Status: field of systemctl status shows the text the process last
published. Before loading the unit, validate it:
# systemd-analyze verify /usr/local/lib/systemd/system/handbook-heartbeat.service
The command checks syntax, executables, and referenced files; it prints nothing on success. Then load and start it:
# systemctl daemon-reload
# systemctl start handbook-heartbeat.service
$ systemctl is-active handbook-heartbeat.service
active
Section 8.2.1 already showed the resulting status output, including the
Status: "heartbeat running" line the process published through the notify
socket.
8.3.2. Service Users, Working Directories, and Environment Files
Who runs the service, and where, is visible from the running instance. As root, start the service - Section 8.2.2 left it disabled and stopped:
# systemctl start handbook-heartbeat.service
Then read the process identity from john's shell:
$ systemctl show -p MainPID --value handbook-heartbeat.service
91608
$ ps -o user:16=,pid=,args= -p 91608
handbook-app 91608 python3 /opt/handbook-heartbeat/heartbeat.py
The PID will differ on your system; the point is the first column - the
process belongs to handbook-app, not root. The directory and environment
settings from the unit file are queryable the same way:
$ systemctl show -p WorkingDirectory -p StateDirectory -p LogsDirectory -p EnvironmentFiles handbook-heartbeat.service
EnvironmentFiles=/etc/handbook-heartbeat/heartbeat.env (ignore_errors=no)
WorkingDirectory=/var/lib/handbook-heartbeat
StateDirectory=handbook-heartbeat
LogsDirectory=handbook-heartbeat
EnvironmentFiles names the file the manager parsed at start time, and
WorkingDirectory is where the process finds its relative paths - the
heartbeat writes heartbeat.state there. The two directory settings did
their job at start:
$ ls -ld /var/lib/handbook-heartbeat /var/log/handbook-heartbeat
drwxr-x--- 2 handbook-app handbook-app 4096 Nov 19 11:31 /var/lib/handbook-heartbeat
drwxr-xr-x 2 handbook-app handbook-app 4096 Nov 19 11:31 /var/log/handbook-heartbeat
Both directories exist and both are owned by the service account; the
state directory carries the 0750 mode from StateDirectoryMode=, while
the log directory keeps the LogsDirectory default of 0755 - tighten it
with LogsDirectoryMode= if the log files themselves warrant it.
Prefer these directives over hand-created directories: the manager creates
them on first start and re-asserts ownership and mode on every start, so
a missing directory or an account change cannot produce the permission
failures dissected in Section 8.8.2. The directories outlive the unit -
removing them when the service is retired is an explicit rm -rf.
The environment file's identity, set up in Section 8.3.1, matters to the
one reader that is not root: the manager parses the file at start time
with full privileges, but the heartbeat's own reload path below re-reads
it as handbook-app, so the group read access is what lets a reload
pick up changes. Confirm it on a running system:
# stat -c "%U:%G %a %n" /etc/handbook-heartbeat/heartbeat.env
root:handbook-app 640 /etc/handbook-heartbeat/heartbeat.env
EnvironmentFile= is read once, when the unit starts. The heartbeat
therefore also passes its own path through Environment=, and the program
re-reads the file when it receives SIGHUP - which is what reload sends.
Watch the whole loop: as root, change the interval, reload, and read the
journal:
# sed -i "s/HEARTBEAT_INTERVAL=5/HEARTBEAT_INTERVAL=2/" /etc/handbook-heartbeat/heartbeat.env
sed -i edits the file in place and prints nothing. Then:
# systemctl reload handbook-heartbeat.service
# journalctl -u handbook-heartbeat.service -g "reloaded" -n 2 --no-pager
Nov 19 11:27:52 client1 systemd[1]: Reloaded handbook-heartbeat.service - Handbook heartbeat service.
Nov 19 11:27:52 client1 handbook-heartbeat[91608]: reloaded interval=2s
The second line proves the application re-read the file and now ticks every
two seconds - without restarting, and with the same PID as the ps output
above. The message-matched read of Section 8.2.1 matters here more than
ever: with the interval now two seconds, a fixed tail window would lose the
reload records almost immediately. This only works because the program
handles SIGHUP; a program that ignores the signal needs a restart to pick
up configuration changes, and there is nothing systemd can do about
that.
8.3.3. Drop-In Overrides and daemon-reload
Suppose the restart delay needs to grow from two seconds to five, and a
label needs to mark this host's copy of the service - without editing the
unit file installed under /usr/local/lib. A drop-in does both. Contents of
/etc/systemd/system/handbook-heartbeat.service.d/10-interval.conf:
[Service]
RestartSec=5
Environment=HEARTBEAT_ROLE=lab
After writing it, tell the manager to re-read everything:
# systemctl daemon-reload
As ever, silent. Now systemctl cat shows both fragments in evaluation
order:
$ systemctl cat handbook-heartbeat.service
# /usr/local/lib/systemd/system/handbook-heartbeat.service
[Unit]
Description=Handbook heartbeat service
Documentation=file:/opt/handbook-heartbeat/heartbeat.py
After=network.target
StartLimitIntervalSec=30
StartLimitBurst=3
[Service]
Type=notify
User=handbook-app
Group=handbook-app
WorkingDirectory=/var/lib/handbook-heartbeat
EnvironmentFile=/etc/handbook-heartbeat/heartbeat.env
Environment=HEARTBEAT_ENV_FILE=/etc/handbook-heartbeat/heartbeat.env
ExecStart=/opt/handbook-heartbeat/heartbeat.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=2
TimeoutStartSec=10
StateDirectory=handbook-heartbeat
StateDirectoryMode=0750
LogsDirectory=handbook-heartbeat
StandardOutput=journal
StandardError=journal
SyslogIdentifier=handbook-heartbeat
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/handbook-heartbeat.service.d/10-interval.conf
[Service]
RestartSec=5
Environment=HEARTBEAT_ROLE=lab
And the effective values - RestartSec overridden, the label added to the
environment, the file-sourced HEARTBEAT_INTERVAL still separate:
$ systemctl show -p Environment -p RestartUSec handbook-heartbeat.service
RestartUSec=5s
Environment=HEARTBEAT_ENV_FILE=/etc/handbook-heartbeat/heartbeat.env HEARTBEAT_ROLE=lab
Note what Environment= does not show: values from EnvironmentFile= are
kept in their own property (EnvironmentFiles in Section 8.3.2) and are
not merged into Environment. Single-value keys take the drop-in's value;
list keys accumulate, as the ExecStartPre reset pattern in Section 8.1.2
showed. When the override is no longer wanted, one command removes every
drop-in installed under the unit's .d directory - without hunting for
file names:
# systemctl revert handbook-heartbeat.service
Removed '/etc/systemd/system/handbook-heartbeat.service.d/10-interval.conf'.
Removed '/etc/systemd/system/handbook-heartbeat.service.d'.
revert also removes a shadowing unit file in /etc, restoring the vendor
definition. systemctl cat now shows only the original fragment again.
Finish the exercise by putting the interval back and restarting cleanly:
# sed -i "s/HEARTBEAT_INTERVAL=2/HEARTBEAT_INTERVAL=5/" /etc/handbook-heartbeat/heartbeat.env
# systemctl restart handbook-heartbeat.service
Both commands are silent; the restart picks up the restored interval.
8.3.4. Restart Policies, Start Limits, and Readiness
The heartbeat declares Restart=on-failure with a two-second delay. The
full policy menu:
Restart= |
Restarts the unit when it ended... |
|---|---|
no |
never (the default) |
on-success |
cleanly (exit status 0) |
on-failure |
uncleanly: non-zero exit, signal, timeout, or failed watchdog |
on-abnormal |
by signal or timeout, but not by a non-zero exit |
on-abort |
by a signal it did not handle itself |
on-watchdog |
after an unacknowledged watchdog ping |
always |
any which way - except a deliberate systemctl stop |
A deliberate stop never triggers a restart, under any policy. Confirm what the running unit uses:
$ systemctl show -p Restart -p RestartUSec -p NRestarts handbook-heartbeat.service
Restart=on-failure
RestartUSec=2s
NRestarts=0
Kill the main process the hard way and watch the policy respond:
$ systemctl show -p MainPID --value handbook-heartbeat.service
65473
# kill -KILL 65473
Two seconds later the unit is active again, and the counter says so:
$ systemctl show -p NRestarts -p ActiveState handbook-heartbeat.service
NRestarts=1
ActiveState=active
The journal shows the sequence systemd followed:
# journalctl -u handbook-heartbeat.service -n 20 --no-pager
Nov 19 09:00:25 client1 handbook-heartbeat[65473]: heartbeat 2026-11-19T09:00:25+0000
Nov 19 09:00:30 client1 handbook-heartbeat[65473]: heartbeat 2026-11-19T09:00:30+0000
Nov 19 09:00:32 client1 systemd[1]: handbook-heartbeat.service: Main process exited, code=killed, status=9/KILL
Nov 19 09:00:32 client1 systemd[1]: handbook-heartbeat.service: Failed with result 'signal'.
Nov 19 09:00:34 client1 systemd[1]: handbook-heartbeat.service: Scheduled restart job, restart counter is at 1.
Nov 19 09:00:34 client1 systemd[1]: Starting handbook-heartbeat.service - Handbook heartbeat service...
Nov 19 09:00:35 client1 handbook-heartbeat[65531]: starting pid=65531 interval=5s
Nov 19 09:00:36 client1 systemd[1]: Started handbook-heartbeat.service - Handbook heartbeat service.
Selected output; earlier heartbeat lines and the stop that preceded the
restart were omitted. status=9/KILL is the same fact the Result=
property records. Stop the unit normally and note that the counter resets,
because a clean stop ends the cycle:
# systemctl stop handbook-heartbeat.service
$ systemctl show -p NRestarts handbook-heartbeat.service
NRestarts=0
Restart policies without limits are a footgun: a service that fails
instantly would spin forever. The heartbeat caps bursts at three starts in
thirty seconds. The next demonstration unit, handbook-crash.service,
fails immediately and restarts as fast as its policy allows. Contents of
/etc/systemd/system/handbook-crash.service:
[Unit]
Description=Handbook crash loop demonstration
StartLimitIntervalSec=10
StartLimitBurst=2
[Service]
Type=simple
ExecStart=/bin/false
Restart=always
RestartSec=1
[Install]
WantedBy=multi-user.target
After systemctl daemon-reload as root, start it:
# systemctl start handbook-crash.service
The command prints nothing and exits 0 - the same Type=simple trap
that Section 8.8.2 dissects: the start job completes the moment
/bin/false is forked, and the loop begins a fraction of a second later.
The unit's state and the journal show the loop and the cutoff:
# systemctl is-failed handbook-crash.service
failed
# journalctl -u handbook-crash.service -n 40 --no-pager
Nov 19 08:44:03 client1 systemd[1]: Started handbook-crash.service - Handbook crash loop demonstration.
Nov 19 08:44:03 client1 systemd[1]: handbook-crash.service: Main process exited, code=exited, status=1/FAILURE
Nov 19 08:44:03 client1 systemd[1]: handbook-crash.service: Failed with result 'exit-code'.
Nov 19 08:44:04 client1 systemd[1]: handbook-crash.service: Scheduled restart job, restart counter is at 1.
Nov 19 08:44:04 client1 systemd[1]: Started handbook-crash.service - Handbook crash loop demonstration.
Nov 19 08:44:04 client1 systemd[1]: handbook-crash.service: Main process exited, code=exited, status=1/FAILURE
Nov 19 08:44:04 client1 systemd[1]: handbook-crash.service: Failed with result 'exit-code'.
Nov 19 08:44:05 client1 systemd[1]: handbook-crash.service: Scheduled restart job, restart counter is at 2.
Nov 19 08:44:05 client1 systemd[1]: handbook-crash.service: Start request repeated too quickly.
Nov 19 08:44:05 client1 systemd[1]: handbook-crash.service: Failed with result 'exit-code'.
Nov 19 08:44:05 client1 systemd[1]: Failed to start handbook-crash.service - Handbook crash loop demonstration.
Selected output; the same pattern repeats for a second run of the exercise
later in the journal. Two starts in ten seconds, then the cutoff:
Start request repeated too quickly. From that moment the unit is failed,
and even systemctl start is refused until the failure is cleared - the
limit exists precisely so a broken service cannot consume the machine:
# systemctl reset-failed handbook-crash.service
$ systemctl is-failed handbook-crash.service
inactive
is-failed exits 1 for a unit that is not failed. Readiness is the last
piece. A Type=notify unit is only "started" once it announces itself;
if it never does, the start job eventually times out. Contents of
/etc/systemd/system/handbook-notready.service:
[Unit]
Description=Handbook readiness timeout demonstration
[Service]
Type=notify
ExecStart=/bin/sleep 10
TimeoutStartSec=3
/bin/sleep never sends READY=1, so it can never be ready. After a
daemon-reload, starting it fails after three seconds:
# systemctl start handbook-notready.service
Job for handbook-notready.service failed because a timeout was exceeded.
See "systemctl status handbook-notready.service" and "journalctl -xeu handbook-notready.service" for details.
$ systemctl status handbook-notready.service --no-pager
× handbook-notready.service - Handbook readiness timeout demonstration
Loaded: loaded (/etc/systemd/system/handbook-notready.service; static)
Active: failed (Result: timeout) since Thu 2026-11-19 09:01:18 UTC; 2s ago
Invocation: b41d26df5fc146ffb9e9605cfdf9a9be
Process: 65800 ExecStart=/bin/sleep 10 (code=killed, signal=TERM)
Main PID: 65800 (code=killed, signal=TERM)
Mem peak: 1.8M
CPU: 7ms
Result: timeout is the fourth result value in this chapter's set, and the
main process was terminated with SIGTERM when the patience ran out. The
journal names the exact phase:
# journalctl -u handbook-notready.service -n 8 --no-pager
Nov 19 09:01:15 client1 systemd[1]: Starting handbook-notready.service - Handbook readiness timeout demonstration...
Nov 19 09:01:18 client1 systemd[1]: handbook-notready.service: start operation timed out. Terminating.
Nov 19 09:01:18 client1 systemd[1]: handbook-notready.service: Failed with result 'timeout'.
Nov 19 09:01:18 client1 systemd[1]: Failed to start handbook-notready.service - Handbook readiness timeout demonstration.
Selected output; an identical earlier sequence from a previous run of the
exercise was omitted. TimeoutStartSec=3 made the window short for the
demonstration; the default is far more generous (90 seconds), and slow-starting
services should either raise it or become notify services that say when
they are actually ready. Remove the practice unit:
# rm -f /etc/systemd/system/handbook-notready.service
# systemctl daemon-reload
Both silent.