Why isn’t the systemd service waiting for the network

networkingsystemd

Per this question and its answers, I've added the following to my service file:

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

I've also run:

systemctl enable NetworkManager-wait-online.service
systemd-networkd-wait-online.service

And yet my ExecStartPre task which uses git pull origin master still fails because of what appears to be a connectivity issue.

Mar 22 16:17:21 COMPUTER git[1983]: ssh: Could not resolve hostname github.com: Name or service not known
Mar 22 16:17:21 COMPUTER git[1983]: fatal: Could not read from remote repository.

Am I missing something obvious? Is there another service I need to wait for in order to use git pull? (In case it's relevant, I'm using Ubuntu 16.10 and systemd 231.)

Best Answer

First step is to determine if you're using NetworkManager or systemd-networkd. Enable wait-online for the one you are using (assuming systemd-networkd for this example):

systemctl enable systemd-networkd-wait-online.service

Have your service start after the wait-online service:

[Unit]
...
After=systemd-networkd-wait-online.service
Requires=systemd-networkd-wait-online.service

(requires is a stricter variant of wants, in this case it seems like you want the hard dependency).

This should cause your service to start after the network is guaranteed up.


Alternatively (or in conjunction with the previous solution) you can configure the service to restart when it fails using the Restart= flag:

[Unit]
...
Restart=on-failure
RestartSec=5

https://www.freedesktop.org/software/systemd/man/systemd.service.html#Restart=

This might be the better method, because it wont slow your boot (https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/#cutthecraphowdoimakenetwork.targetworkforme - using wait-online is liable to slow your boot-time considerably), but if you're worried about what the service might do when it fails, go for option 1 or both.

Related Question