The key to understanding how to get a service to stop at shutdown prior to losing the network is knowing that the shutdown order is the reverse startup order. Therefore, your service should start after network-online.target
while also having a dependency on network-online.target
, because it requires the network to be up. Furthermore, there are ExecStart=
and ExecStop=
actions that you can define. Since you want the script to run at shutdown, which is when the service stops, you want to define ExecStop=
pointing to your script.
To set this up, do the following:
- In the [Unit] section, create a
Requires=network-online.target
dependency
- Set the order to
After=network-online.target
.
- In the [Service] section, don't define an
ExecStart=
action.
- Set
RemainAfterExit=true
, because we didn't create an ExecStart=
action.
- Finally, create an
ExecStop=
action pointing to your script, such as ExecStop=/home/username/bin/testscript.sh
.
Remember, the shutdown order is the reverse startup order. Therefore, when your service is stopped, your script, which is placed in ExecStop=
, will be run. And because we started this service after network-online.target
, it will be shutdown before any services in network-online.target
are shutdown.
As an example...
Here is a simple test script that uses curl
to get your public IP address. As such, DNS is required for this to run properly.
#!/bin/bash
# NAME: testscript.sh
# PATH: /home/username/bin
NOW=`date`
IP=`curl -s https://ipinfoio/ip`
echo $NOW $IP >> /home/username/ipaddresses
Next, create a systemd service/unit file in /etc/systemd/system
. I named this testservice.service
.
[Unit]
Description:Test service to execute at shutdown prior to losing network
Requires=network-online.target
After=network-online.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/home/username/bin/testscript.sh
[Install]
WantedBy=multi-user.target
Tell systemd to read our file:
sudo systemctl daemon-reload
Enable the service:
sudo systemctl enable testservice.service
Then reboot the system and you will see that the file /home/username/ipaddress
will be updated with a timestamp at shutdown and your public IP address.