Docker: Connect to host from container on Linux

Dominik Rüttiger 1 min read

If you’re coming from the Mac, you’re probably used to connecting to the host from inside a container with the address host.docker.internal. On Linux, however, this does not work out of the box.

Docker CLI

If you run the following command on a Linux machine, you will see that DNS resolution is not working:

docker run --rm alpine ping -c 1 host.docker.internal

To fix this, we need to set the DNS name manually:

docker run --add-host=host.docker.internal:host-gateway --rm alpine ping -c 1 host.docker.internal

Instead of host.docker.internal you could use any other name.

Docker Compose

To achieve the same result in Docker Compose, use the extra_hosts property.

Create a docker-compose.yml file:

version: "3.9"

    image: alpine
      - "host.docker.internal:host-gateway"

Test it with:

docker-compose run --rm test ping -c 1 host.docker.internal

Further reading




Twitter Hacker News Reddit