Categories
SysOps

How to restart systemd service in case of failure

Configure systemd service to be restarted in case of failure.

By default, the service will be marked as failed after five consecutive starts in ten seconds.

$ cat /etc/systemd/system.conf | grep StartLimit
#DefaultStartLimitIntervalSec=10s
#DefaultStartLimitBurst=5

Create a drop-in configuration directory and define the following parameters to restart the service (honeycreeper in this example) every ten seconds in case of failure.

$ sudo mkdir -p /etc/systemd/system/honeycreeper.service.d
$ cat <<EOF | sudo tee /etc/systemd/system/honeycreeper.service.d/restart.conf
[Unit]
StartLimitIntervalSec=0
[Service]
Restart=always
RestartSec=10
EOF
$ sudo systemctl daemon-reload

In case of failure, the service will be restarted endlessly.

$ sudo systemctl status honeycreeper
● honeycreeper.service - honeycreeper
     Loaded: loaded (/etc/systemd/system/honeycreeper.service; enabled; vendor preset: enabled)
    Drop-In: /etc/systemd/system/honeycreeper.service.d
             └─restart.conf
     Active: activating (auto-restart) (Result: exit-code) since Sun 2020-08-23 19:19:37 CEST; 6s ago
       Docs: man:honeycreeper(1)
             file:/usr/share/doc/honeycreeper/configuration.txt.gz
    Process: 614105 ExecStartPre=/usr/sbin/honeycreeper -f $CONFIG -c -q $EXTRAOPTS (code=exited, status=1/FAILURE)

Service will not be marked as failed because it is using the permanent auto-restart feature.

$ sudo systemctl --failed
  UNIT LOAD ACTIVE SUB DESCRIPTION
0 loaded units listed.