docker networking with vpn in container

There are many quirks, tricks, and caveats of container networking.

One trick I have used to my advantage was how a VPN works within a container.

I was working on a system that had to change VPN connections every few hours. Easy enough, I just wrote a Golang application which uses OpenVPN to switch the VPN at a set interval.

However if run directly on the host, this would mean that any other ongoing network connections would be dropped each time the VPN was switched.

To mitigate this, I installed openVPN inside a Docker container, and then put my Golang VPN switching application inside this container.

Then, give the container the --privileged and --net=host flags so that it can properly bind to the host network interface(s).

Now, within the container, I am connected through a VPN. However on the host, I am still connected through my original connection.

As the VPN connection changes within my container, my network connection on my host remains unaffected.

Another plus (or caveat, depending on the situation) - other containers using --net=host will connect through the VPN as well.

This effectively allows you to have a "VPN Management" container, and then various application containers which can make use of the shared VPN connection.

last updated 2022-08-20