Accessing services on the host from a Docker container or a Podman one

August 18, 2023 [Docker, Podman, Programming, Tech]

I use Podman to provide Docker-like stuff on my dev machine without effectively being root.

Talking to the container host in Docker

There is a little trick for accessing HTTP services on the container host in Docker: you add --add-host host.docker.internal:host-gateway to the command line when you run the docker container, for example:

docker run -d --add-host host.docker.internal:host-gateway my-container:latest

Now in your code you can refer to the Docker container host using the name host.docker.internal.

Talking to the container host in Podman

However, this doesn't work in Podman. Instead, you need to add --network slirp4netns:allow_host_loopback=true to the command line, for example:

docker run -d --network slirp4netns:allow_host_loopback=true my-container:latest

Now in your code you can refer to the Podman container host using the name host.containers.internal.

Supporting both

For this to work in both Docker and Podman, your container needs to know which framework it is working inside, and use either host.docker.internal or host.containers.internal explicitly, which is a pity.