Docker Tip #65: Get Your Docker Host's IP Address from in a Container
Once in a while you may need your Docker host's IP address. Here's how to do it on Docker for Mac, Windows and Linux.
In Docker Tip #35 I wrote about connecting to your Docker host from inside of a container but a lot of things have changed since then. Here’s a more updated version.
Docker for Mac / Docker for Windows
As of Docker v18.03+ you can use the
host.docker.internal hostname to connect to your Docker host.
This could come in handy if you wanted to connect to a database that’s running on your host but isn’t running inside of a container.
I often see this use case come up when people are beginning to move their stack over into using Docker. If that’s the case you would just use
host.docker.internal as your DB connection host.
Docker for Linux
There’s a couple of ways to do this, but the easiest way would be to connect over the IP address listed in your
docker0 network adapter.
If you ran
ip a on your Docker host you might see something similar to this:
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 link/ether 02:42:e8:a9:95:58 brd ff:ff:ff:ff:ff:ff inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0 valid_lft forever preferred_lft forever
Using the above output as an example, you could connect to your Docker host from inside of a container by using this IP address:
If you expect that IP address might change you could go the extra mile and do something like
docker container run -e "DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+')" ..., this way every time you run your container, it’ll have the IP address available inside the container set to the
DOCKER_HOST environment variable.