Forward Connection to Docker in Linux

Published by Torry Crass on

Every now and then it is necessary to set up a connection forwarding from external to inside the system perhaps to a docker instance where the internal IP for the docker is a completely separate subnet from your host system (192.168.*.* vs 172.16.*.* for example) .

One possible way to accomplish this could be to use netcat or socat to accept and forward. However, this isn’t always the most ideal way, especially if you want it to easily persist over reboots.

IPTables is another great option to accomplish this with two rule additions. For this example we’ll do this for an elasticsearch docker instance.

First, you need to make sure the docker container is able to be connected to and the second rule adds a PREROUTING nat rule to take the host traffic and send it to the docker instance.

9200 is the port of the docker service you’re attempting to access
172.18.0.3is the IP address of the docker container (see below if you need to know how to get ip information).
0.0.0.0/0indicates that we will accept connections from ANY ip address, you may want to restrict this.

iptables -A DOCKER -p tcp -m tcp --dport 9200 -s 0.0.0.0/0 -d 172.18.0.3 -j ACCEPT

iptables -t nat -A PREROUTING -p tcp --dport 9200 -j DNAT --to-destination 172.18.0.3:9200

That should do it. You can check this by simply telneting to the port from an allowed network/system.

To find the IP address of a docker container you can run the following command:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' CONTAINERID


1 Comment

Torry Crass · September 22, 2019 at 9:08 pm

You may also need to turn on ip forwarding at the kernel level. The link below has some information on how to do that via sysctl.

https://serverfault.com/questions/801894/set-up-port-listening-and-forwarding

Leave a Reply