Docker networking games

One of the very few niceties of Docker Desktop is the inclusion of a special DNS name: host.docker.internal that resolves to the one of the host's internal IPs, typically encompassed by binding a host service to localhost.

On a semi-Docker-focused side-project with a friend we use pytest for integration testing, and some of these tests create and destroy images, containers, networks, and other resources.

In one of the tests, a container needs to reach a Python service listening on the host. Specifying the Docker network gateway IP is not tenable as this varies between environments. Aha! Let's use host.docker.internal! This works very well, but only within Docker Desktop installations. Damn.

Despite conditional configuration to accommodate multiple platforms not being the cleanest way around problems, it will occasionally have to do. If we pass the following Docker CLI argument along with a docker run or docker create we can replicate this functionality in a normal dockerd environment:

docker run --add-host=host.docker.internal:host-gateway [...]

This will create a runtime DNS record (think /etc/hosts) to map host.docker.internal to the gateway IP of the attached Docker network—which will tend to be an IP anchored on the host.

May this help someone who asks, "Why is host.docker.internal not resolving in my container?"