Search code examples
raspbiansystemd

How to automatically restart systemd service on failure?


I have written this service that runs TCP server using node.js to take data from micro controller to mysql server.

root@DietPi:~# sudo cat /lib/systemd/system/mysqlwifi.service 
 [Unit]
 Description=MySQL exampledb update
 After=multi-user.target
 After=network-online.target
 Wants=network-online.target

 [Service]
 Type=idle
 ExecStart=/usr/bin/node /home/dietpi/node_server/mysqlwifi.js > /home/dietpi/node_server/mysqlwifi.log 2>&1

 [Install]
 WantedBy=multi-user.target
root@DietPi:~#

Since this service is critical to push data to mysql i want it to automatically restart on failure. I also want to know how can I send an email on each failure or when service comes back live.


Solution

  • [Service]
    Restart=on-failure
    

    Setting Restart=on-failure to your unit configuration should do it, but check Restart documentation for more options. To send an email you could use an ExecStartPost= clause with a mailx call.