When using MacOSX and Docker you currently need Docker Machine. A problem that you’ll run into very soon is port forwarding. For example when starting tomcat:
$ docker run -it --rm -p 8888:8080 tomcat:8.0
This expose tomcat on port 8888 on the host and maps it to port 8080 in the container. So you should be able to just navigate to “http://localhost:8888” in the browser but on Mac you’ll end up with this instead:
Since docker is running in VirtualBox on Mac we need to forward a port to the docker-machine VM as well. There are many different ways to do this but I think they are all a bit cumbersome to remember. For this reason I created a small bash script to make it easier to remember how to do port forwarding.
The name of this bash script is `pf` (which stands for port forward). It allows you to create a port mapping as easily as this (after you’ve started the docker container):
$ pf 8080
This forwards port 8080 in the container to port 8080 on the host in the docker-machine environment name `default` by opening an SSH connection to VirtualBox in the background.
If you run into this error:
Host does not exist: "default"
you’ll need to specify the name of your docker-machine environment. For example:
$ pf 8080 -e dev
This will use the `dev` docker-machine environment.
But what if you want to use a different port on the host? Just do:
$ pf 8888:8080
This will map port `8888` on the host to `8080` in the container.
Stopping the port forwarding
If you’ve started port forwarding in the background (default) you can easily stop it using:
$ pf 8080 -s
Where `8080` is the host port. You can also do:
$ pf 8888:8080 -s
but `8888` would be enough. Note that there’s also no need to specify the environment when stopping the port forwarding (using `-e`).
Running in Foreground
There may be cases where you’d rather want to run the “port forwarding process” in the foreground. This is also very easy, just add `-f`:
$ pf 8080 -f
If you do this you’ll see the docker-machine console and once it’s shutdown the port forwarding is also stopped automatically (i.e. no need to run `pf 8080 -s`).
This script makes it easy to remember how to do port forwarding with docker-machine on Mac. There are more options available in the script and if you want to know more just run:
$ pf -h
Note that if you need more advanced options just use the vanilla `docker-machine` command. The purpose of `pf` is to make it really easy to do the most basic things. Don’t forget to visit the github page if you find this useful.
Thanks for the handy script. Sometimes the port is required to accept connections from any machine. When it is needed, add an additional ssh option ‘-g’ is to line 125 of pf.sh or make ‘-g’ an option like ‘-f -N’.