Systemd - start service only after DNS is available

Try using:

[Unit]
After=network-online.target
Wants=network-online.target

There's a full write-up on Unix & Linux as well as on the FreeDesktop site.


Not a proper solution to my problem, and almost certainly not going to pass my code review, but maybe helpful for someone else.

I placed an exec start prerequisite in my ntp and nginx unit files to continue trying to resolve a name before continuing on.

ExecStartPre=/bin/bash -c 'until host example.com; do sleep 1; done'

So, I have the same dilemma with a remote mount cifs drive that needs to be mounted via DNS FQDN rather than IP. I tried a batch of things, but so far I have to agree with Brando's solution (short of writing an entire Systemd service and pulling it in before the .mount or network-online.target).

The only alternative to Brando's that I have found (that actually works in practice, rather than just in theory from the man pages) is to swat the fly with a sledge hammer, and put an ExecStartPre= into systemd-networkd-wait-online.service:

[Service]
...
ExecStartPre=/bin/sleep 15

If you are keen, you can also append to the ExecStart= using --interface=interface_name (and optionally --timeout=). This helps because I have a vlan sub interface, but wait-online was just tracking the first of any interfaces (loop back excluded) that would come online. By itself though, it didn't fix the problem.

I though using -o _netdev within the mount definition of /etc/fstab would fix it (and in theory in Systemd remote drives wait for the network-online.target by default), but alas, no dice. Listing the dependencies of the resultant mnt-remote.mount file does show that network-online.target is a precursor, but DNS still failed. Manually running the service post boot works fine, I'm just getting screwed by some sort of race condition between the target coming up and DNS actually resolving prior to the mount process happening. That, and the fact that the definition of an 'online' interface varies from person to person and case to case (my use case requires DNS, others obviously don't - a topic that is covered extensively on FreeDesktop: https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget).

Brando's solution is more elegant. This one also needs trial an error to minimise the sleep time but still have it work reliably, subject to how long it takes your DHCP/DNS/NIC to get all sorted out.

I throw this out there as an inferior solution just in case Brando's doesn't work for you for some reason.

Another work around would be to punch an entry into the local hosts file, but I wasn't interested in doing that for a case where the IP to FQDN changes on a relatively frequent basis (similar issue with just mounting it using the IP in the first place).