2026-10-28
Most small services need the same four things: a non-root user, a low port, a directory for state, and a restart when they crash. systemd does all four without a wrapper script.
[Service]
ExecStart=/usr/local/bin/myservice -config /etc/myservice/config.json
User=myservice
Group=myservice
StateDirectory=myservice
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
Restart=on-failure
RestartSec=3
AmbientCapabilities=CAP_NET_BIND_SERVICE lets an unprivileged process bind ports below 1024. It replaces both running as root and setcap on the binary, which is lost every time the binary is replaced.
StateDirectory=myservice creates /var/lib/myservice owned by the service user. With ProtectSystem=strict the rest of the file system is read-only, so this is the one place the service can write.
Restart=on-failure restarts after a crash but not after a clean exit, so systemctl stop still means stop.
systemd-analyze security myservice prints a score and the list of settings that are still open. It is a checklist, not a grade: a service that has to talk to the network will never reach the top of it.