Expose Port Inside Running Container on Docker Toolbox for Mac

Tags: July 20, 2016 11:05 PM

Problem

Docker only allows to define port that need to be exposed when doing container creation. When the container already running and new port need to be exposed, you're out of luck.

Goal

You want to expose new port which run by application inside a running container, so you can hit the docker-vm-ip:port to access the port on Mac OS X.

Assumptions

  • IP of Boot2Docker VM (Which run by Virtualbox) is 192.168.99.100
  • IP of the docker container running the application is 172.17.0.2
  • The application listen on address 0.0.0.0 and port 80

Steps

  1. SSH to the Boot2Docker using user "docker" and password "tcuser"
    $ ssh docker@192.168.99.100
    docker@192.168.99.100's password: 
                            ##         .
                      ## ## ##        ==
                   ## ## ## ## ##    ===
               /"""""""""""""""""\___/ ===
          ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
               \______ o           __/
                 \    \         __/
                  \____\_______/
     _                 _   ____     _            _
    | |__   ___   ___ | |_|___ \ __| | ___   ___| | _____ _ __
    | '_ \ / _ \ / _ \| __| __) / _` |/ _ \ / __| |/ / _ \ '__|
    | |_) | (_) | (_) | |_ / __/ (_| | (_) | (__|   <  __/ |
    |_.__/ \___/ \___/ \__|_____\__,_|\___/ \___|_|\_\___|_|
    Boot2Docker version 1.11.2, build HEAD : a6645c3 - Wed Jun  1 22:59:51 UTC 2016
    Docker version 1.11.2, build b9f10c9
    docker@default:~$
    
  2. Forward the port from 192.168.99.100:80 to 172.17.0.2:80
    $ sudo iptables -t nat -A PREROUTING -d 192.168.99.100/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.17.0.2:80
    
Done. Now just try to connect from Mac OS X host to the Boot2Docker IP. It should forwarded to the application inside the container.
$ curl -i http://192.168.99.100
You can repeat as many as you want for other port.

Reference

Share on Facebook Twitter

0 comments:

Post a Comment