Press "Enter" to skip to content

Docker Machine Port Forwarding

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:

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.

Introducing pf

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):

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:

you’ll need to specify the name of your docker-machine environment. For example:

This will use the dev docker-machine environment.

But what if you want to use a different port on the host? Just do:

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:

Where 8080 is the host port. You can also do:

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:

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:

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.


  1. Nikhil Owalekar Nikhil Owalekar February 4, 2017


  2. TH Lim TH Lim February 16, 2017

    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 or make ‘-g’ an option like ‘-f -N’.

Leave a Reply

Your email address will not be published. Required fields are marked *