So I will assume that you have a container connected to a VPN server and you need to access a server through this container due to IP restrictions and so on.
1- In case you are using Bridge Network which is the default when you run a container:
In order to achieve you will need to have IPTables installed inside the container and after starting the VPN connection run the following command:
iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
And from the host machine where you want to access a service you can use iproute
command to route the connection through the container as below:
Assuming you want to access a remote server with IP 192.168.0.20 through a container with IP: 172.17.0.4
ip route add 192.168.0.20 via 172.17.0.4
Now whenever you access the server which is 192.168.0.20 it will be through the VPN client inside your container.
2- You can pass --network=host
to docker run
and in this case you wont need any extra steps to do as the connection will be routed through the VPN by default
Update:
Given that you have a Container Y with port 9000 and accessible through Container X.
Container X is connected to a VPN.
A User connected to the same VPN wants to access Container Y and he should go through Container X, then you need to apply the following firewall rules inside Container X
iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
iptables -t nat -A PREROUTING -i tun0 -p tcp --dport 9000 -j DNAT --to-destination $CONTAINER_Y_DOCKER_IP
iptables -t nat -A POSTROUTING -p tcp -d $CONTAINER_Y_DOCKER_IP --dport 9000 -j SNAT --to-source $CONTAINER_X_DOCKER_IP
iptables -A FORWARD -m state -p tcp -d $CONTAINER_Y_DOCKER_IP --dport 9000 --state NEW,ESTABLISHED,RELATED -j ACCEPT