神刀安全网

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 :

$ dockerrun -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:

Docker Machine Port Forwarding

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

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

Hostdoesnot 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 ).

Conclusion

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.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Docker Machine Port Forwarding

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮