4

I wrote a pretty simple service:

[Unit]
Description=Service on interface %I

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/lib/project/my_script.sh start %I

[Install]
WantedBy=multi-user.target

Which I start like systemclt start myservice@net0, where net0 is a network interface. How can I restart the service every time the network interface is restarted?

  • There usually are if-up.d, if-down.d, or if-postdown.d, if-preup.d respectively on your system somewhere in /etc. They contain scripts that are called before an interface comes up or after it goes down. Not sure though if it triggers when you simply change the IP address... – Marki Oct 6 '14 at 16:24
  • Those are only present on Debian/Ubuntu IIRC. Definitely not with systemd-networkd (I was talking about adding them the other day, they resisted). – CameronNemo Oct 8 '14 at 6:03
  • That means that, for now, is not possible to do what I'm trying? – José Luis Oct 8 '14 at 14:37
12

You can have your systemd unit bind (BindTo) and depend on (DependsOn) the .device unit for the corresponding network interface (which is automatically loaded) for the said interface as so:

[Unit]
Description=Service on interface %I
BindsTo=sys-subsystem-net-devices-%i.device
After=sys-subsystem-net-devices-%i.device

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/lib/project/my_script.sh start %I

[Install]
WantedBy=multi-user.target

You'll probably want to have the unit's dependency formalized by adding Wants and After if your custom unit expects to have the network interface actually online by adding these in the [Unit] section:

Wants=network-online.target
After=network-online.target

NB: You can verify that .device units are loaded by doing systemctl list-units --type=device.

  • 1
    What if I want to restart if ip changes on any interface ?! any idea ? I don't want to BondTo every present interfaces, I would like to use something dynamic. but I can't figure out the proper Service/device to listen to. – Elmatou Jan 4 '18 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.