Skip to content

Lesson 2 of 9 · 28m

Unit Files Thoroughly: Sections, Types, and Execution

The anatomy of a production-grade service unit: what belongs in [Unit], [Service], and [Install], how types change readiness, and the directives people misuse most.

Most broken units I review misuse the basics: wrong Type, a shell command forced into ExecStart, or environment assumptions copied from a login shell. systemd units are declarative configuration, not init scripts wearing a new hat.

A realistic service unit

[Unit]
Description=Acme metrics API
Documentation=https://ops.example.internal/services/metrics-api
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
User=metrics
Group=metrics
ExecStart=/opt/metrics/bin/metrics-api --config /etc/metrics/config.yaml
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5s
EnvironmentFile=-/etc/metrics/environment
WorkingDirectory=/var/lib/metrics
UMask=0027

[Install]
WantedBy=multi-user.target

Every line has a job. Description appears in logs, Documentation helps the 3 a.m. responder, and WantedBy determines enablement.

The three sections

[Unit] describes metadata and relationships. [Service] describes how the process runs: executable, restart policy, user, environment, limits, and hardening. [Install] describes how the unit is attached to the boot graph; only enabled units need it.

Type is a readiness contract

  • simple/exec: the process stays foregrounded; startup means executed, not necessarily ready.
  • notify: the program calls sd_notify("READY=1") when sockets and state are actually ready.
  • forking: traditional daemons fork and exit; use PIDFile= when available.
  • oneshot: run once and exit, often for setup jobs.

Do not mark a forking daemon as simple because it "works." systemd may track the launcher shell rather than the real daemon.

Exec lines are not shell commands

# wrong: pipe syntax is not interpreted
ExecStart=/opt/app/server 2>&1 | tee /var/log/app.log
# right: stdout already goes to the journal
ExecStart=/opt/app/server --log-level=info

If shell expansion is truly required, write it explicitly and use exec so the shell does not remain the service process:

ExecStart=/bin/sh -c 'exec /opt/app/server --workers "$WORKER_COUNT"'

Overrides beat vendor edits

Use systemctl edit postgresql.service; it writes a drop-in under /etc/systemd/system/postgresql.service.d/. systemctl cat postgresql.service shows the merged result. Never edit /usr/lib/systemd/system/postgresql.service directly.

Field notes

  • Services do not inherit your interactive shell environment or PATH customization.
  • A leading - in EnvironmentFile=-/path makes a missing file non-fatal.
  • Use absolute paths in every Exec* line.
  • Run systemctl daemon-reload after editing units; systemd does not treat unit files as live-reload configuration.

Was this lesson helpful?

Sign in to rate