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.internalgateway.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:
- Start a simple HTTP server with port 8000 using the
python -m http.server 8000command. For Python 2.x, you can use thepython -m SimpleHTTPServer 8000command. - Build your Docker container and install curl using either the
apt-get update && apt-get install -y curlorapk add curlor any other preferred way of installation. - Try to connect from the container to your host using the following command:
shell
1curl http://host.docker.internal:80002exitPlease 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 bash2curl http://host.docker.internal:80003exitTo 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.
