systemd Units & Services

Unit files, service types, dependency ordering, socket activation, and service hardening directives.

Overview

systemd is the init system and service manager on virtually all modern Linux distributions. It parallelizes service startup by tracking inter-service dependencies.

Unit File Locations

  • /usr/lib/systemd/system/ — distribution packages (do not edit)
  • /etc/systemd/system/ — admin overrides (preferred)
  • ~/.config/systemd/user/ — user units

Service Types

  • simple (default) — main process is ExecStart
  • forking — daemon forks; PIDFile must be set
  • notify — process sends sd_notify("READY=1") when ready
  • oneshot — completes and exits

Dependency Keywords

  • Requires= — hard dependency
  • Wants= — soft dependency
  • After= / Before= — ordering only; Requires= does not imply After=

Hardening Directives

PrivateTmp, NoNewPrivileges, ProtectSystem=strict, CapabilityBoundingSet — implement least-privilege for system services.

Key concepts

Service type=notify
Service sends sd_notify("READY=1") when initialization is complete. systemd waits before starting dependent services.
After= vs Requires=
After=network.target means start after networking (ordering only). Requires=postgresql.service means fail if postgres is not running (dependency).
WantedBy=multi-user.target
Running systemctl enable creates a symlink in multi-user.target.wants/, causing the service to start at boot.
Restart=on-failure
Automatically restart if the service exits with a non-zero exit code. Combine with RestartSec=5 to prevent tight crash loops.
Socket activation
systemd holds the listening socket open and passes it to the service on first connection. The service can restart without dropping connections.

When to use it

  • Writing a systemd service for a custom application (API server, background worker)
  • Diagnosing why a service fails to start with "Failed to start" in systemctl status
  • Hardening a service unit to run with minimal privileges

Interview questions

  • Write a systemd service unit for a Node.js API server that should restart on failure and start after the network is up.
  • Your systemd service is stuck in "activating" state. How do you diagnose it?

Sign up free to read the full topic

More Linux topics

Start free on Cariara · Coding problems · System design studio