Docker container cannot resolve hosts

By default creating a new docker container also creates a virtual network that separates the docker network environment from the host network environment (somewhat). This allows one to easily spin up multiple containers which might all listen on the same port (e.g. 80), but in a way that can be mapped to unique ports on the host machine (e.g. service1:80 -> host:8080, service2:80 -> host:8081).

docker run YOUR_IMAGE --network="host" will bind the container network adapter to that of the host machine. This should allow you to access the host machine via listening port of the host machine. e.g. localhost:8080 However you need to remember that ports are a scarce resource and you cannot have conflicting port listeners in different containers when you do this.

You can also retrieve the host’s ip address from within a docker container depending on your OS and docker version:

Mac/Windows:
As of Docker v18.03+ you can use the host.docker.internal hostname to connect to your Docker host.

Linux:
docker container run -e "DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+')" will make the host IP available from within the docker container as an environment variable: DOCKER_HOST

Leave a Comment

tech