Expose new ports for running docker container

  • fennng 
When you use docker run to start a new docker container, you can use -p option to map a docker container port to a localhost port.
For example:
docker run –name wp1 -p 8080:80 wordpress
This will create a docker container running wordpress named wp1 and map localhost:8080 to wp1:80
Because your localhost and wp1 are not in the same network, you cannot access wp1 directly, but you can access wp1:80 from localhost:8080 to access wordpress website.
If your localhost (host machine) is a VM has a public IP address, you can use public_ip:8080 to access your wordpress website. But then you suddenly realize that 8080 port is not open to public, only 80 port is. And for some reason, you cannot rerun the docker container. Now, how can you remap wp1:80 to localhost:80?
Because docker containers in the same network can access each other though docker containers’ names or ip addresses, we can create a new docker container as a bridge to access the running one. I will introduce three methods here.
1. Using reserve Proxy
We can run a reserve proxy such as nginx .  This way is a bit complex, I will not discuss it here.
2. Using socat to do port forwarding
docker run -ti -p 80:8082 –rm  bobrik/socat TCP4-LISTEN:8082,fork TCP4:wp1:80
one simple command will solve the problem. Let me explain this a little bit.
 bobrik/socat TCP4-LISTEN:8082,fork TCP4:wp1:80
This part starting a socat which listens to port 8082, and will forward all the traffic to 8082 to wp1:80.
the ,fork here is important, otherwise, socat will only forward the first request and exit.
-p 80:8082 will map socat container’s 8082 port to localhost 80.
So, the reqeust come to VM’s port 80 will be forward to socat’s 8082 port, then socat will forware it to wp1:80, and finally reach the destination.
3. Using SSH to do the port forwarding
 
docker run -d -P –name test_sshd -p 2222:22 rastasheep/ubuntu-sshd
 
Then remap localhost:80 to wp1:80 using ssh command
 
ssh -N -L 80:wp1:80 root@localhost -p 2222
 
In this command ssh root@localhost -p 2222 is a normal ssh connection, the magic happens here -N -L 80:wp1:80, this remap localhost:80 to wp1:80 using test_sshd as a bridge.
标签:

发表评论

您的电子邮箱地址不会被公开。