How to automatically restart Linux services with Systemd

Getting your Linux deployments working reliably is of paramount concern for production applications. One way to guarantee that a service is always available is to ensure that it is automatically restarted in the event of a crash, and Systemd provides the necessary tools to make it happen.

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.

/etc/systemd/system/daemon.service
[Unit]
Description=Your Daemon Name

[Service]
ExecStart=/path/to/executable
Restart=on-failure
RestartSec=1s

[Install]
WantedBy=multi-user.target

In the above service configuration file, Restart is set to on-failure so 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 StartLimitIntervalSec and 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.

/etc/systemd/system/daemon.service
[Unit]
Description=Your Daemon Name
StartLimitIntervalSec=300
StartLimitBurst=5

[Service]
ExecStart=/path/to/executable
Restart=on-failure
RestartSec=1s

[Install]
WantedBy=multi-user.target

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!