Search code examples
dockerlocalhostdocker-machine

Connect to docker-machine using 'localhost'


There are certain features, like JavaScript service workers without https, that only work on localhost, but when I run my app inside a docker container, using docker-compose, which runs on top of docker-machine, I need to connect to it using the address I get from

docker-machine ip default

Is there a way to map localhost to that ip?


Solution

  • You can add a VirtualBox port forward to map a port on the docker host to your local machine.

    Assuming your docker machine is called "default" and you want to map port 80 in your container to localhost:8888 you can run:

    vboxmanage modifyvm default --natpf1 "nameformapping,tcp,,8888,,80"
    

    or if the VM is running

    vboxmanage controlvm default natpf1 "nameformapping,tcp,,8888,,80"
    

    This can also be done in the VirtualBox UI in the settings for the VM. Here is the doc from VirtualBox https://www.virtualbox.org/manual/ch06.html#network_nat

    You'll also need to map the port on your container to the port on the docker machine, you do that when you start the container (this also assumes that you have a "EXPOSE 80" command in your Dockerfile

    docker run -p 80:80 mycontainer
    

    https://docs.docker.com/engine/reference/run/

    Also see: https://github.com/boot2docker/boot2docker/blob/master/doc/WORKAROUNDS.md