Open ports to docker container
How to open ports at container launch
Here's the standard way. Let's use port 80 on our local machine to access port 8080 on the docker image.
$ docker run -d -p 80:8080 springio/gs-spring-boot:latest
And grab the IP addres
$ echo $DOCKER_HOST
$ firefox $DOCKER_HOST:8080
How to open ports manually with SSH tunneling
Let's say you create a container and want to run something like a Spring Boot app on it. The container gets a private ip accessible to the virtual machine running it, your desktop or laptop only knows the address of that virtual machine and nothing in it.
Let's solve that problem with an ssh tunnel to it!
Give yourself ssh access to the virutal machine
Copy your public key
copy ~/.ssh/id_rsa.pub to clipboard
Connect to your virtual machine
docker-machine ssh local
Now add your key to authorized keys
vim ~/.ssh/authorized_keys
Now exit back to your terminal
Create a tunnel to the container running on the virtual machine
List the virtual machines running and grab it's ip address
docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS default - virtualbox Stopped Unknown local * virtualbox Running tcp://192.168.99.100:2376 v1.10.2
Now we need the ip of the container running on that virtualmachine, but first lets start the container
$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE springio/gs-spring-boot 1.0-SNAPSHOT 1eef2782ff99 2 hours ago 195.1 MB hello-world latest 690ed74de00f 5 months ago 960 B
Now start it
$ docker run springio/gs-spring-boot:1.0-SNAPSHOT
Now let's grab the containers id
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f39c5f11e51f springio/gs-spring-boot:1.0-SNAPSHOT "java -Djava.security" 23 minutes ago Up 23 minutes angry_raman
docker inspect f39c5f11e51f
"Networks": { "bridge": { ... "Gateway": "172.17.0.1", "IPAddress": "172.17.0.2", ... } }
Now launch the tunnel
ssh -L 1234:<container ip>:8080 docker@<machine ip>
Doing so will allow you to visit localhost:1234, and see what's on the remote 8080 machine.