Back to questions
MiddleCodeOccasional
Complete a systemd service unit that restarts the daemon on failure.
Complete this systemd service unit for a long-running daemon.
Constraints: it must restart automatically on failure with a short delay, and it must start at boot once enabled. Fill in the missing directives — do not change ExecStart.
[Unit]
Description=My App
After=network.target
[Service]
ExecStart=/usr/bin/myapp
# 1) restart the daemon automatically when it exits with a failure
# 2) wait a few seconds between restarts
[Install]
# 3) which target should pull this unit in at boot?Add the restart directives and the install target, then say how you activate it.
In [Service] add Restart=on-failure so systemd relaunches the daemon on a non-zero exit, plus RestartSec=5. In [Install] add WantedBy=multi-user.target so enable links it into that boot target. Then run systemctl enable --now myapp: enable wires it for boot, --now starts it now.
- Putting
RestartorWantedByin the wrong unit section - Thinking
systemctl startalone makes a unit survive a reboot - Omitting
[Install] WantedBy, soenablehas no target to link into
- What does
systemctl daemon-reloaddo after you edit a unit file? - How does
Restart=on-failurediffer fromRestart=always?
Solution
[Unit]
Description=My App
After=network.target
[Service]
ExecStart=/usr/bin/myapp
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.targetRestart=on-failuremakes systemd relaunch the daemon whenever it exits non-zero (a crash);RestartSec=5spaces the retries so it does not hot-loop. For "restart even on a clean exit" you would useRestart=alwaysinstead.WantedBy=multi-user.targetin[Install]is whatenableacts on: it creates a symlink undermulti-user.target.wants/, so the unit is pulled in at that boot target (the runlevel-3 equivalent). Without an[Install]section,enablehas nothing to link.- Activate it in two steps with one command:
systemctl daemon-reload # reread the file after editing
systemctl enable --now myapp # enable = start at boot, --now = start it right nowenable creates the symlink for future boots but does not start the service now; start runs it now but does not survive a reboot. --now does both.