Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing host machine as localhost from a Docker container that's also inside a boot2docker vm

Suppose I have a server running on port 8000 on OSX. How can my Docker container access it via localhost:8000? I can't change the hostname too as the app in the container is not in my control.

I've read this previous discussion on using --net="host" for a container to access the host machine's network. However, I'm on OSX and Docker runs inside a VM so localhost from the Docker container with --net="host" goes to the VM and not my real machine.

Then I tried port forwarding workaround like so: VBoxManage modifyvm "boot2docker-vm" --natpf1 "tcp-port8000,tcp,,8000,,8000"; to no avail.

Any suggestion would be greatly appreciated.

like image 246
Paul Lam Avatar asked May 28 '15 01:05

Paul Lam


People also ask

How do I access the host machine from Docker containers?

Docker Desktop 18.03+ for Windows and Mac supports host.docker.internal as a functioning alias for localhost. Use this string inside your containers to access your host machine. localhost and 127.0.0.1 – These resolve to the container. host.docker.internal – This resolves to the outside host.

What is localhost in Docker container?

After that, the localhost (127.0.0.1) in your Docker container will point to the host Linux machine.This runs a Docker container with the settings of the network set to host. This container will share the network with the host machine and the container’s localhost will point to the host machine.

Do I need boot2docker's IP address to run a docker container?

That way, you do not have to use boot2docker's IP address: you can use localhost or your own IP address (and your docker container can be accessed from outside).

Does the host networking driver work with Docker Desktop for Windows?

The host networking driver only works on Linux hosts, and is not supported on Docker Desktop for Mac, Docker Desktop for Windows, or Docker EE for Windows Server. Create and start the container as a detached process.


2 Answers

Thanks to palimpestor's answer I figured it out:

Instead of --net="host", use --add-host="localhost:10.0.2.2"

Indeed:

  • 10.0.2.2 is the default gateway defined for the guest network interface in NAT mode (reference).
    Read: it's your host, seen from boot2docker.
  • --add-host... is adding localhost 10.0.2.2 in /etc/hosts (reference)

Note: you need to have set up a NAT adapter in your boot2docker VM VirtualBox settings (I did it through the GUI, don't know the CLI).

like image 173
lajarre Avatar answered Oct 14 '22 06:10

lajarre


Instead of running with --net="host", try --add-host="localhost:192.168.59.3", which is the boot2docker host IP.

like image 17
palimpsestor Avatar answered Oct 14 '22 04:10

palimpsestor