How to Connect to the Host Machine from a Container on Docker for Mac

I was recently working on a mac-based dev environment and need to proxy from a container running nginx (to handle HTTPS connections) to a server running on the host machine. Docker’s host network mode does not work on MacOS as expected given that docker is running inside a VM rather than directly in the host’s operating system.

There’s a little section of of the docker for mac networking guide that covers the work around: use host.docker.internal which will resolve to the MacOS machine (not the virtual machine running docker).

Example with an Nginx Proxy

To return to the Nginx thing hinted at above. Should we need to proxy from nginx in a docker container to the host machine, we can use that special host name.

server {
  location / {
    # you may want `X-Forwarded-Host` here. Doing it this way mimics
    # my prod environment (which uses an AWS ALB) that doesn't send
    # an `X-Forwarded-Host`.
    proxy_set_header Host $host;

    # the rest of this are help play nice with Symfony's (PHP)
    # routing and http foundation components so urls are generated
    # correctly with the https protocol and correct port.
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-Port $server_port;

    # Tell nginx to proxy back to the host machine
    proxy_pass http://host.docker.internal:8009;
  }
}

This special host.docker.internal hostname can be used anywhere something in a container might need to call back to the host from a container. The downside is that this appears to only work on Docker for Mac and Windows, but not linux where a host network mode would work as expected.