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='vpn.your-server.com'
ENV VPN_SERVER_CERT='your cert if needed'
ENV VPN_LOGIN='your.username'
ENV VPN_PASSWORD='YourPassword'
# install VPN utils
RUN apt-get install -y openvpn openconnect
Create the following bash script that connects the Docker container to the VPN server:
#!/bin/bash
if [ -z "$VPN_SERVER_CERT" ]
then
echo $VPN_PASSWORD |openconnect -u $VPN_LOGIN $VPN_SERVER --passwd-on-stdin -b
else
echo $VPN_PASSWORD |openconnect -u $VPN_LOGIN $VPN_SERVER --servercert $VPN_SERVER_CERT --passwd-on-stdin -b
fi
# Wait a little
sleep 5
# Print IP
curl http://api.ipify.org
# 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 VPN_SERVER=vpn.foo.com \
-e VPN_LOGIN=mylogin \
-e VPN_PASSWORD=mypass \
vpn-docker-img-name /app/start.sh