Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Port forwarding in docker-machine?

Since boot2docker is deprecated I've switched to docker-machine but I don't know how to open a port from docker-machine. In boot2docker I could do like this:

boot2docker ssh -L 27017:localhost:27017 

This would forward port 27017 from VirtualBox to localhost 27017 as long as the SSH connection is open. Note that I'm not looking for a way to open the port permanently in VirtualBox. How can I achieve this with docker-machine?

like image 740
Johan Avatar asked Aug 24 '15 04:08

Johan


People also ask

How do I port forward a Docker container?

To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world.

Does Docker require IP forwarding?

Docker relies on the host being capable of performing certain functions to make Docker networking work. Namely, your Linux host must be configured to allow IP forwarding.

What is the use of port in Docker?

In Docker, the containers themselves can have applications running on ports. When you run a container, if you want to access the application in the container via a port number, you need to map the port number of the container to the port number of the Docker host. Let's look at an example of how this can be achieved.


2 Answers

You can still access the VBoxmanage.exe command from the VirtualBox used by docker machine:

VBoxManage controlvm "boot2docker-vm" natpf1 "tcp-port27017,tcp,,27017,,27017"; 
  • Use docker-machine info to get the name of your vm.
  • use modifyvm if the vm isn't started yet.

See a practical example in this answer.


That is the current workaround, pending the possibility to pass argument to docker-machine ssh: see issue 691.

The other workaround is to not forward port, and use directly the IP of the VM:

 $(docker-machine ip default) 

As commented by sdc:

You can confirm that port forwarding is set up correctly with

 VBoxManage showvminfo boot2docker-vm | grep "NIC.* Rule"  
like image 142
VonC Avatar answered Sep 28 '22 04:09

VonC


With recent versions of machine, you can simply do (where default is the name of the machine):

docker-machine ssh default -L 27017:localhost:27017 

This is a more temporary solution than the VM configuration change.

Use the following variation to only forward ports in a background process:

docker-machine ssh default -f -N -L 27017:localhost:27017 
  • -f Requests ssh to go to background just before command execution.
  • -N Allow empty command (useful here to forward ports only)
like image 41
David Avatar answered Sep 28 '22 03:09

David