Use VPN in Docker container with OpenConnect

For a new project I needed to call an API from within a micro service that was running as Docker container. Usually this would not be a big deal. However, the API is a private API and, therefore, it is only accessible from within a virtual private network (VPN).

I struggled for while to get everything running. So I hope these snippets can help you. You basically just need to install OpenConnect to your image, add a small script to build the connection at start time and run the container as privileged.

Add the following lines to your Dockerfile (only tested for Debian-based images):

# Define environment variables
ENV VPN_SERVER_CERT='your cert if needed'
ENV VPN_LOGIN='your.username'

# install VPN utils
RUN apt-get install -y openvpn openconnect 

Create the following bash script that connects the Docker container to the VPN server:


if [ -z "$VPN_SERVER_CERT" ]
    echo $VPN_PASSWORD |openconnect -u $VPN_LOGIN $VPN_SERVER --passwd-on-stdin -b
    echo $VPN_PASSWORD |openconnect -u $VPN_LOGIN $VPN_SERVER --servercert $VPN_SERVER_CERT --passwd-on-stdin -b

# Wait a little
sleep 5

# Print IP

# Run your regular commands
# ...

To start the your container run the following command (--privileged is required to make it work):

docker run -it \
    --privileged \
    -e \
    -e VPN_LOGIN=mylogin \ 
    -e VPN_PASSWORD=mypass \       
    vpn-docker-img-name /app/