Connecting to Docker Host from Docker Container

Alex KondratievAlex Kondratiev

4 min read

Learn how to connect from a Docker container to the Docker host. This capability can be handy for development tasks such as managing other containers, performing backups, or building a simple admin interface to manage them.


Sometimes, containers need to communicate with the Docker host. You can use the feature to start, stop, and check the status of other containers: let's say you have scheduled backup software. Before backing up, you need to stop your containers and restart them afterward. Or maybe you want to create a simple web interface for more accessible control over your containers? Even simpler: you want to connect to a cloud or database to fetch or remove the data. See below for how to do this!

For this purpose, Docker exposes special DNS names:

  • host.docker.internal
  • gateway.docker.internal

This solution works out of the box on macOS and Windows. To achieve the same on Linux (Docker 20.10+), add --add-host=host.docker.internal:host-gateway or set it in docker-compose.

The ability to connect to a Docker host from inside of a docker container came with the release of version 18.03  for macOS and Windows, although Docker did not support the function for Linux until late 2020.

To check whether a container can communicate with the host, you can use Python. It is relatively straightforward and will require only several minutes:

  1. Start a simple HTTP server with port 8000 using the python -m http.server 8000 command. For Python 2.x, you can use the python -m SimpleHTTPServer 8000 command.
  2. Build your Docker container and install curl using either the apt-get update && apt-get install -y curl or apk add curl or any other preferred way of installation.
  3. Try to connect from the container to your host using the following command:

shell

1curl http://host.docker.internal:8000
2exit

Please note that if you are using Linux, you need to run your Docker container with appropriate flags before executing the curl command. Otherwise, the curl will yield you an error. See the correct build sequence below:

shell

1docker run -it --add-host=host.docker.internal:host-gateway ubuntu bash
2curl http://host.docker.internal:8000
3exit

To have a more consistent Docker behaviour, you can add host.docker.internal:host-gateway into your Docker compose file.

Note! Please note that this will work for development purposes only; production environments outside of Docker Desktop should use proper DNS.
Alex Kondratiev

Alex Kondratiev

Founder of ITsyndicate. DevOps Enthusiast with 15+ years of experience in cloud, Infrastructure as Code, Kubernetes, and automation. Specialized in architecting secure, scalable, and resilient systems.

Plan the present.
Build the future.