Connecting to a host service from within a container using Docker for Mac

1 minute read

TL;DR

Use host.docker.internal.


When you are running Docker on Linux and want to access services on the host from within a container, you can make use of the docker0 bridge interface (ip a s docker0). This does not work when running Docker for Mac as the interface is inside a separate virtual machine (which you can confirm by getting a shell in that vm: screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty) and thus not visible on the local host.

To workaround this, a reliable way to get to the macOS host is to use the host.docker.internal DNS name which will always resolve to an IP where the host is reachable.

Example

Let’s say you want to run some script in the container that connects to a specific HTTP target and want to observe the requests through a proxy running on your macOS machine (e.g. Burp). Then you would do:

# Run some container
docker run -it alpine:latest /bin/sh

# ... install the dependencies for your script ...
# then run the script and target your local (!) intercept proxy
python3 exploit.py http://host.docker.internal:8081/whatever

# now observe the request in the proxy application running on the host

Capturing the request

Like to comment? Feel free to send me an email or reach out on Twitter.

Did this or another article help you? If you like and can afford it, you can buy me a coffee (3 EUR) ☕️ to support me in writing more posts. In case you would like to contribute more or I helped you directly via email or coding/troubleshooting session, you can opt to give a higher amount through the following links or adjust the quantity: 50 EUR, 100 EUR, 500 EUR. All links redirect to Stripe.