When defining services in a docker-compose file, when do I use host.docker.internal
for the host’s ip and when do I need to use the container’s name?
When defining services in a docker-compose file, when do I use host.docker.internal
for the host’s ip and when do I need to use the container’s name?
2
Answers
If you want to connect from a container to a service on the host, use
host.docker.internal
. Be aware, that this special DNS name is only available on Windows and macOS.Use the container name for networking between containers.
All possible communication flows are illustrated here :
(1) : non-containerized process communicates with a container
(2) : container communicates with another container
(3) : the opposite direction of (1)
(1): container must forward port to host, so the non-containerized process can access it
(2): container c1 just use the service name (container name – c2) to communicate with c2
(3): container c2 must Use the private IP of the host(
hostname -i
).For (3), there are couple of points:
Host Network range must not overlap with Docker network range, otherwise, Docker router will not throw the request out.
Host must not enable firewall that blocks ports used by the non-containerized process.
IF you are using Docker For Desktop,
host.docker.internal
is alias to the Host private IP. then you don’t need to calculate the private IP of the host withhostname -i
.