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:

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

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

Terminal window
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:

docker-compose.yml
version: '3.9'
services:
test:
image: alpine
extra_hosts:
- 'host.docker.internal:host-gateway'

Test it with:

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

Further reading

Tags

#devops #docker #dx #linux

Share

Twitter LinkedIn Hacker News Reddit