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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With