How do you make systemd restart a service automatically if it crashes?
Set Restart=on-failure (or always) in the [Service] section, usually with RestartSec= to add a delay. systemd then restarts the process after a crash, and StartLimitBurst and StartLimitIntervalSec stop endless crash loops.
Explain it simply
A guard who stands up again every time he falls, but who stops trying if he has fallen five times in a minute.
In the [Service] section:
Restart=on-failure
RestartSec=5Common values of Restart=:
no: never (the default).on-failure: restart on a non-zero exit, a signal, or a timeout, but not on a clean exit.always: restart no matter how it stopped, even after a clean exit.on-abnormal,on-abortfor narrower cases.
RestartSec=5 waits five seconds before restarting, which avoids hammering a failing dependency.
To prevent infinite loops, systemd limits attempts: StartLimitBurst=5 with StartLimitIntervalSec=60 means more than five starts in 60 seconds puts the unit into failed. Use systemctl reset-failed name afterwards.
A systemctl stop is intentional, so it is not restarted. Apply changes with daemon-reload then restart.
Example
sudo systemctl edit myapp # creates a drop-in override
# [Service]
# Restart=on-failure
# RestartSec=5
sudo systemctl restart myapp
sudo kill -9 $(systemctl show -p MainPID --value myapp)
systemctl is-active myapp
# activeWhat to say in the interview
"I set Restart=on-failure with a RestartSec delay in the unit, preferably via a systemctl edit drop-in. systemd also rate-limits restarts with StartLimitBurst, so a crash loop ends in failed instead of looping forever."
Common mistakes
- Using Restart=always on a job that should exit cleanly, so it restarts endlessly.