TExcelTAD
Home › Linux Server Administration › Writing a Service Unit

Writing a Service Unit

A service unit tells systemd how to start a process, which user it runs as, what to do when it exits and how to stop it. Getting these few keys right is most of what makes an app behave like a proper server daemon.

A production-shaped service

ini
[Unit]
Description=Inventory API
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
Type=exec
User=inventory
Group=inventory
WorkingDirectory=/opt/inventory
EnvironmentFile=/etc/inventory/env
Environment=PORT=8000 LOG_FORMAT=json
ExecStartPre=/opt/inventory/bin/inventory check-config
ExecStart=/opt/inventory/bin/inventory serve
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=2s
TimeoutStopSec=20s

[Install]
WantedBy=multi-user.target

Type=: when is the service "started"?

systemd needs to know when a start has finished, so that units ordered after it can start. That is what Type= decides:

Type "Started" when… Use for
simple (default) right after fork(), before the program even runs quick tests; errors like a missing binary are reported late
exec the binary was executed successfully most apps: a typo in ExecStart= makes systemctl start fail
notify the program calls sd_notify("READY=1") daemons with readiness support (PostgreSQL, systemd-aware Go/Rust apps)
forking the started process exits, leaving a daemonised child old-style daemons that fork themselves; pair with PIDFile=
oneshot the process exits successfully setup jobs, backups, scripts started by timers

Don't daemonise inside a service. Run your app in the foreground and let systemd supervise it: no &, no nohup, no --daemon flag. Logs go to stdout/stderr and land in the journal automatically.

Restarting: Restart= and the start limit

Restart= Restarts after…
no (default) never
on-failure non-zero exit, killed by a signal, timeout, watchdog
on-abnormal signal, timeout, watchdog (not a clean non-zero exit)
always any exit, even exit code 0

RestartSec= waits between attempts (default 100 ms). To stop a crash loop from burning CPU forever, systemd also has a start rate limit: by default more than 5 starts within 10 s (StartLimitBurst=5, StartLimitIntervalSec=10s, both in [Unit]) puts the unit into the failed state with the result start-limit-hit. With the default 100 ms delay a broken app hits that limit within seconds. A model of the interplay:

python · try it yourself
def simulate(restart_sec, burst=5, interval=10.0, crash_after=0.5, horizon=60.0):
    """App crashes `crash_after` s after each start; systemd restarts it after `restart_sec`."""
    t, starts = 0.0, []
    while t < horizon:
        recent = [s for s in starts if t - s < interval]
        if len(recent) >= burst:
            return f"RestartSec={restart_sec:>4}: start-limit-hit at t={t:.1f}s after {len(starts)} starts"
        starts.append(t)
        t += crash_after + restart_sec
    return f"RestartSec={restart_sec:>4}: still restarting after {horizon:.0f}s ({len(starts)} starts)"

for delay in (0.1, 1.0, 2.0):
    print(simulate(delay))
RestartSec= 0.1: start-limit-hit at t=3.0s after 5 starts
RestartSec= 1.0: start-limit-hit at t=7.5s after 5 starts
RestartSec= 2.0: still restarting after 60s (24 starts)

A delay of 2 s keeps a flapping app under the limit, so it keeps retrying (good while a database is briefly down); a short delay gives up quickly. Choose consciously, and alert on units in the failed state.

Environment and secrets

  • Environment=KEY=value for non-secret settings; several on one line or several lines.
  • EnvironmentFile=/etc/inventory/env for values managed outside the unit; prefix with - (EnvironmentFile=-/etc/…) to make the file optional. Make it root:inventory, mode 0640.
  • Secrets in environment variables are visible to the same user via /proc/<pid>/environ. systemd's LoadCredential= (and LoadCredentialEncrypted=) passes a file into $CREDENTIALS_DIRECTORY instead, readable only by the service.

Checking the whole file

Type=oneshot is the only type allowed several ExecStart= lines, and ExecReload= needs a real command. systemd-analyze verify checks both, and it also checks that the binaries exist:

bash · try it yourself
cat > backup.service <<'EOF'
[Unit]
Description=Nightly database dump

[Service]
Type=oneshot
ExecStart=/usr/bin/mkdir -p /tmp/backups
ExecStart=/usr/bin/tar -czf /tmp/backups/etc.tar.gz /etc/hostname
EOF
systemd-analyze verify ./backup.service && echo "backup.service: OK"

cat > api.service <<'EOF'
[Unit]
Description=Inventory API

[Service]
Type=exec
ExecStart=/opt/inventory/bin/inventory serve
ExecStart=/opt/inventory/bin/inventory metrics
EOF
systemd-analyze verify ./api.service
echo "exit code: $?"
sed -i '$d' api.service              # keep one ExecStart= line
systemd-analyze verify ./api.service
echo "exit code: $?"
backup.service: OK
api.service: Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.
Unit api.service has a bad unit file setting.
exit code: 1
api.service: Command /opt/inventory/bin/inventory is not executable: No such file or directory
exit code: 1

Two real problems in api.service, found one after the other: a non-oneshot service with two ExecStart= lines (run two services instead), then a binary that does not exist on this machine. On a real server you would only meet the second one at start time; verify finds it before you deploy, as long as you run it on a machine (or image) laid out like the target.

Stopping cleanly

On systemctl stop, systemd sends SIGTERM (KillSignal=) to the main process (and, with the default KillMode=control-group, to every process in the service's cgroup), waits TimeoutStopSec= (default 90 s), then sends SIGKILL. Your app should catch SIGTERM, finish in-flight requests and exit within that time. A shorter TimeoutStopSec= makes deploys and reboots faster; one shorter than your app's drain time cuts requests off.

Test yourself

Why is Type=exec usually better than the default Type=simple?

  1. It uses less memory
  2. systemctl start only succeeds once the binary was actually executed, so a wrong path fails the start instead of failing later
  3. It restarts automatically
  4. It allows several ExecStart lines

A service crashes immediately on every start and has Restart=on-failure with the default RestartSec. What happens?

  1. It restarts forever
  2. After 5 starts within 10 seconds it hits the start limit and enters the failed state
  3. systemd reboots the server
  4. It is restarted once

Which service type may have more than one ExecStart= line?

  1. simple
  2. exec
  3. notify
  4. oneshot