How to make a Linux systemd service wait for a VPN interface before starting

Like me, you may have a requirement for a service to start only once a VPN interface is established.

This is quite easy to achieve by extending the systemd unit file for the service in question. In this example, based upon Ubunutu 16.04 but portable to other systemd-based distros, I will focus on docker.service, but the configuration is applicable to any service – provided you change the relevant folder/ filenames, in bold, appropriately.

For a service other than docker.service, find and replace “docker.service” with the relevant service name you want to wait for VPN connectivity.

You also need to identify the systemctl device id for you VPN connection.

# Identify the VPN interface name - commonly "tun0"

# Find the systemctl interface name based upon output from command above. In my case this output "sys-devices-virtual-net-tun0.device"
systemctl | grep tun0

With the systemctl device name, and having replaced docker.service if required proceed.

sudo mkdir /etc/systemd/system/docker.service.d/
sudo touch /etc/systemd/system/docker.service.d/depend.conf
sudo vi /etc/systemd/system/docker.service.d/depend.conf

# New conf file should only contain lines below

# Now save the file and exit vim

# Reload systemd daemons
sudo systemctl daemon-reload

# Test container connectivity following a reboot