A useful feature that is often needed for long-running processes such as web servers is the ability to automatically restart the process in the event of a crash in order to minimise downtime. If your service is being managed by Systemd, you can use the Restart and RestartSec options to configure this behaviour for a particular service.
In the above service configuration file,
Restart is set to
that the service is restarted if the service exits with a non-zero exit code, or
if terminated using a signal (such as using the
kill command for example). The
RestartSec option configures the amount of time to wait before restarting the
service. Here, it’s set to one second to override the default value of 100ms.
After updating your Systemd unit file, ensure to run the command below to ensure your changes take effect:
$ sudo systemd daemon-reload
Two other useful options that you should be aware of are
StartLimitBurst. They are both useful for configuring when Systemd should
stop trying to restart a service. The former specifies a time interval in
seconds, while the latter specifies the maximum amount of times that is allowed
for the service to be restarted within the specified interval.
According to the configuration above, the service is not allowed to restart more than three times within a 300 second interval. If the service crashes more than three times, it will not be permitted to start anymore.
After reloading the systemd manager configuration (
sudo systemctl daemon-reload), kill your running service and confirm that it is automatically
restarted after the time specified by
RestartSec has elapsed.
Thanks for reading!