Total Pageviews

Thursday, 23 June 2016

通过内部ip访问Docker容器

When you run a lot of containers inside of a docker host, you can get lost of the forwarded ports. Let’s say you have 3 instances all exposing 3 ports: 22, 80 and 443. Docker will automatically assign ‘random’ port numbers like:

Now its hard to remember all those ports, and is confusing that if you want to ssh into the first one, you use ssh root@docker -p 49162 and in the browser you would use: http://docker:49163.

There is an even bigger problem with random ports. Wehn your http server sometimes redirects you to https, you need the standard port numbers. The webserver running inside of a docker container, will redirect you to port 443 which will not be correct port (49164 in our case)

So it would be much natural for the docker instances to use their ip address, with straight port numbers. But those ip addresses are only valid inside of the docker host. How to do the magic?

SSH is yor best friend

There is complete SOCKS proxy hidden indide of ssh. To get it alive you just have to toss a -D 1099 parameter, and boom, it will listen on your localhost’s 1099 port and act as a proxy. So here is a how you create an ssh based tunnel :

1

ssh -qTfN2 -D 1099 docker

For the curious the parameter meanings:

q :- be very quite

T :- Do not allocate a pseudo tty

f :- move the ssh process to background

N :- Do not execute remote command.

2 :- Forces ssh to try protocol version 2 only.

docker internal IPs

How can you get the internal ip of a container? You can get all the dirty details by: sudo docker inspect XXXXX. For the moment the only interresting this is the IP addresses. So the oneliner is: