Docker allows developers to efficiently build, test and deploy applications by wrapping them in standardized units called containers. When working with Docker containers, you may encounter scenarios where you want to connect your container with the host.
Linux Equivalent of
Docker versions before
18.03 supported the
host.docker.internal command on Mac and Windows systems only. However, version
20.10.0 of Docker was released in December 2020, and the subsequent versions support using the
host.docker.internal command to connect to the host on Linux machines.
According to the Docker documentation, if the host has a changing IP address, we can connect to the host using
host.docker.internal, which resolves to the internal IP address of the host. However, this can only be used in the development environment.
In Windows and Mac, using the
host.docker.internal to connect to the host is much easier. Suppose we wanted to connect to a MySQL service running on the host’s default port,
We can get the Docker container to connect to this service using the command below.
On a Linux system, on the other hand, we need to add an extra tag before we can successfully connect to the host. This only applies to Docker versions later than
20.10.0 by adding the
--add-host flag alongside the
docker run command.
docker run -d --add-host host.docker.internal:host-gateway new_container
This command adds a new entry to the
etc/hosts director, mapping
host.docker.internal to the host gateway. Alternatively, we can also use
172.17.0.1, also known as
localhost, which is the gateway address for the default bridge network in Docker.
Docker networking is a broad subject, and the above commands or methods can be used differently depending on what you want to accomplish.