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.target
(a crash); RestartSec=5 spaces the retries so it does not hot-loop. For "restart even on a clean exit" you would use Restart=always instead.
symlink under multi-user.target.wants/, so the unit is pulled in at that boot target (the runlevel-3 equivalent). Without an [Install] section, enable has nothing to link.
Restart=on-failuremakes systemd relaunch the daemon whenever it exits non-zeroWantedBy=multi-user.targetin[Install]is whatenableacts on: it creates a- 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 now
enable 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.