Docker Community Forums

Share and learn in the Docker community.

Need portable way to resolve host IP address from inside a container



I have built a solution of 3 docker containers and they all can communicate with each other by resolving using the container names as provided through the hosts file.

The solution is deployed on a machine that already hosts a mysql database and we need to connect to this host machine database to perform specific queries.

We don’t always know what the hosts IP address is going to be (we have a number of hosts this container may be deployed to). Is there any way of getting docker to put the host IP address into the container hosts files?

The other alternative i’ve thought of is passing the host IP address into the container via an environment variable and then getting the container to add it to the hosts file when the container starts up.

Any thoughts?



(Raj Chaudhuri) #2

Passing the host IP is probably for the best. However, if you are willing to take a risk, we can depend on the fact that the default gateway address for the default network interface of any container is usually the host ip address. The following shell script retrieves it.

/sbin/ip route |grep '^default' | awk '/eth0/ {print $3}'

I have tested this on containers (created from the alpine:latest image) on default and private networks.