Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restart systemd service if network connection is down

I have this unit file running as a systemd service. It basically launches a Nodejs Express application running on a Raspberry Pi on local network. The application runs fine but if for some reason the router or network gets down and back up again, the app stops listening and I have to restart the systemd service to get it working again.

[Unit]
Description=Employee Manager PiClock VueJs App
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/home/pi/.nvm/versions/node/v8.9.4/bin/node /home/pi/employee-manager-app/vuejs-app-server/app.js
User=pi
Restart=always
# Restart service after 2 seconds if node service crashes
RestartSec=2

[Install]
WantedBy=multi-user.target

Is there a way to restart the service automatically if the network gets down and up again?

like image 997
Giovanni Bauermeister Avatar asked Feb 08 '18 15:02

Giovanni Bauermeister


People also ask

Can a systemd service restart itself?

It depends on what process is running as the service. If you ran the above script process as a systemd service you could do it. Like a self-updater mechanism written into the process itself. It could even restart itself.

What is the command to restart network service in Linux?

You must run the command as root user either using sudo or su commands. The ifup command bring a network interface up. The ifdown command take a network interface down.

What is network target service?

network-online. target is a target that actively waits until the nework is "up", where the definition of "up" is defined by the network management software. Usually it indicates a configured, routable IP address of some kind. Its primary purpose is to actively delay activation of services until the network is set up.


2 Answers

Systemd targets are reached once and do not fire again when the connection state changes. Depending how your network is managed there are a couple of options:

If you already use NetworkManager you can utilize its dispatcher scripts that fire on network changes.

If you use systemd-networkd you might be able to use networkd-dispatcher that works in a similar way.

For netctl you might use netctl hooks for when your interface comes back up.

wicd as well as many others have similar functionality but as far as I know systemd lacks its own persistent network monitoring.

like image 122
micke Avatar answered Oct 13 '22 05:10

micke


On Fedora 24 through 28 you may use BindsTo=network.service in the [Unit] section.

[Unit]
Description=Employee Manager PiClock VueJs App
Wants=network-online.target
After=network-online.target
BindsTo=network.service

For more, read the man-page of systemd.unit.

like image 28
iamauser Avatar answered Oct 13 '22 05:10

iamauser