Exposing ports on live containers

Sidhartha Mani
2 min readMar 14, 2017

--

TL;DR. Run this command to expose live container with ip 172.17.0.2’s port 3306, to host port 3306.

docker run --privileged -v /proc:/host/proc -e HOST_PORT=3306 -e DEST_IP=172.17.0.2 -e DEST_PORT=3306 wlan0/redirect:latest

I do quite a bit of work on this java server that runs as a docker container. This container exposes the service on port 8080. So, when I start the server, the command I use is

docker run -d -p 8080:8080 java/server

This java service also packages its own mysql image and runs it, unless an external mysql is specified. I was running this server without the external mysql, and I wanted to debug this server.

Specifically, I needed access to the filled mysql database. I could think of a few ways to do this:

  1. Stop the container and start a new one with the added port exposure. `docker run -p 3306:3306 -p 8080:8080 -d java/server`.
  2. The second option is to start another container that links to this, and knows how to port forward.
  3. Setup iptables rules to forward a host port into the container.

I chose the third option, since that is the easiest and requires the least amount of work. The iptables rule to NAT a host port to docker bridge can easily be learned by looking at the existing rules that docker creates. Docker uses iptables too to configure port forwarding from host to containers.

Following existing rules, I created my own rule to forward to the container

iptables -t nat -D DOCKER ! -i docker0 -p tcp --dport 3306-j DNAT --to-destination 172.17.0.2:3306

This just says that whenever a packet is destined to port 3306 on the host, forward it to the container with ip 172.17.0.2, and its port 3306.

Once I did this, I could connect to the container using host port 3306. I wanted to make it easier for others to expose ports on live containers. So, I created a small repository and a corresponding docker image.

The same effect as exposing host port 3306 to container 172.17.0.2:3306 can be achieved using this command. This command saves the trouble of learning how to use iptables.

docker run --privileged -v /proc:/host/proc -e HOST_PORT=3306 -e DEST_IP=172.17.0.2 -e DEST_PORT=3306 wlan0/redirect:latest

I’ve pushed this code to https://goo.gl/hBtMTi

--

--