8

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?

3
  • 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... Commented Oct 6, 2014 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). Commented Oct 8, 2014 at 6:03
  • That means that, for now, is not possible to do what I'm trying? Commented Oct 8, 2014 at 14:37

2 Answers 2

14

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
  • 4
    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. Commented Jan 4, 2018 at 9:20
1

Probably this could work: https://clinta.github.io/run-service-on-ip-change/

# /etc/systemd/system/ip-change-mon.service [Unit] Description=IP Change Monitor Wants=network.target After=network-online.target [Service] ExecStart=:/bin/bash -c "ip mon addr | sed -nu -r \'s/.*[[:digit:]]+:[[:space:]]+([^[:space:]]+).*/\\1/p\' | while read iface; do systemctl restart ip-changed@${iface}.target; done" [Install] WantedBy=multi-user.target default.target 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.