As the title says, I need to be able to retrieve the IP address the docker hosts and the portmaps from the host to the container, and doing that inside of the container.
-
1Could you elaborate on how you'd like to use this information? You said "docker hosts" -- are you running Docker on more than one host? Once your container knows the IP address of the host and portmaps, what will it do? – Andy Apr 08 '14 at 22:56
-
The simplest way to pass the docker host IP addresses to the docker container, I think you should make a call inside the container using 'docker container exec'. Suppose you want to ping the host from inside busybox container, use for example: $ IP = '8.8.8.8' && docker container busybox ping $IP ' The way to find out the host IP, use what you like more. – SauloAlessandre Jan 14 '20 at 20:58
28 Answers
/sbin/ip route|awk '/default/ { print $3 }'
As @MichaelNeale noticed, there is no sense to use this method in Dockerfile
(except when we need this IP during build time only), because this IP will be hardcoded during build time.

- 5,497
- 2
- 20
- 26
-
63When you are using the docker bridge (default) for the containers, this will output the bridges IP like 172.17.42.1 rather than the host's IP such as 192.168.1.x (I'm assuming your host is on a home NAT). Using @Magno Torres answer is probably what people want in such situations if you want the 192.168.1.x address. – Programster Sep 18 '14 at 11:10
-
4that RUN won't work as you expect - it only will calculate the IP at build time - and will forever be static after that, and not useful. It will be the IP of the build host. – Michael Neale Mar 03 '15 at 07:14
-
7@Programster, I can assume people want the connection between docker host and container, that's what bridge IP can give you (of course in the stndard "home" installation). Why anybody would need "real" host IP if it can be even outside of docker bridge and can be unaccessible? This is the solution for all people who just installed docker and want to play with it in a short time. – spinus Mar 04 '15 at 02:56
-
2@MichaelNeale, as before, I would assume that most people who are starting with docker need a connection between their host and container, that's it. If someone is doing "proper" deployments, probably he's not using docker bridge anyway, he's using custom networking and than probably he's aware of all the network quirks or they have DNS (or whatever discovery) set up. – spinus Mar 04 '15 at 02:59
-
1@spinus - but this will only be valid if it runs on the host it was built on - in that case - you can just hard code it - or look it up - I think it isn't a helpful answer and will mislead a lot of people - recommend you remove it. (The RUN bit) – Michael Neale Mar 06 '15 at 00:28
-
1It's worth noting that this option won't work in a minimalist container runtime that strips out a lot of the default Linux utilities. For those cases, passing in the bridge address when running the container will be necessary. – ncoghlan Sep 17 '15 at 08:03
-
1My use case: development environment. Code running on ports 3000 and 3001 of localhost, Docker nginx container to reverse proxy both services to the same virtual host on port 80. Could probably do it with docker-compose, but this is simpler. Technique used not in Dockerfile but in start script that manages nginx config. – Ryan Kennedy Feb 05 '16 at 17:49
-
From host: `docker-compose exec app bash -c "/sbin/ip route|awk '/default/ { print \$3 }'"` – Eduardo Cuomo Apr 24 '17 at 18:59
-
-
Benyamin, if you use some docker images of choice you have to take care of the tools inisde the image. You can install required tool or use different image. – spinus Sep 14 '20 at 12:22
-
This is the answer for those who interpret the question as 'how do I do a call like https://localhost:8888/do_stuff from within a docker container?' in which case hitting the docker bridge is probably the best approach anyway: no need for doing a vm network interface loopback – Rondo Aug 08 '22 at 21:50
As of version 18.03, you can use host.docker.internal
as the host's IP.
Works in Docker for Mac, Docker for Windows, and perhaps other platforms as well.
This is an update from the Mac-specific docker.for.mac.localhost
, available since version 17.06, and docker.for.mac.host.internal
, available since version 17.12, which may also still work on that platform.
Note, as in the Mac and Windows documentation, this is for development purposes only.
For example, I have environment variables set on my host:
MONGO_SERVER=host.docker.internal
In my docker-compose.yml
file, I have this:
version: '3'
services:
api:
build: ./api
volumes:
- ./api:/usr/src/app:ro
ports:
- "8000"
environment:
- MONGO_SERVER
command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi

- 9,564
- 146
- 81
- 122

- 7,325
- 6
- 42
- 71
-
2@allanberry unfortunately the Docker folks prefer not to give us a platform-independent way to do this because they prefer not to embrace unintended use cases (like accessing any service on the local machine from a docker container) – Andy Jan 16 '18 at 04:00
-
@Andy, it seems there is some community demand for it though; perhaps they could maintain control by providing this feature? Perhaps it doesn't have to be platform independent, just more elegant than the accepted answer above – allanberry Jan 16 '18 at 19:55
-
59I was introduced to Docker like _Build it once, run it everywhere._ But this is acutally false since you always have to configure the host system as well. So `docker.for.mac..` is useless since in most cases you don't have a Linux- or Mac-only environment in your company. It's mixed, you have devs using Linux and Mac and Windows. This domain makes no sense since in 99% it's a mixed Host OS environment. I don't develop a container under macOS and deploy it to a macOS server. I deploy it to Linux. This is what everyone does. **So what's even the whole point of `docker.for.mac..`?** – TheFox Mar 16 '18 at 16:08
-
@TheFox the `docker-compose.yml` file doesn't change. In this example, `docker.for.mac...` is set in an environment variable, which yes would have to be different on a Linux box, but the interface is still identical wherever installed. Isn't that exactly what the Docker environment setting is for? – allanberry Mar 16 '18 at 17:03
-
1@allanberry `docker.for.mac.host.internal` doesn't matter whether you are using Docker with or without `docker-compose`. I want to use a fixed host in configuration files. IDK, for example, `docker.host.internal`, which **always** points to the host IP address. Regardless of which host system I'm using. This is the whole point of using Docker at all: I want to be autonomous. I understand that it's even trickier on macOS because you have another layer between the host system and the container. But anyway, in my opinion `docker.for.mac.host.internal` is useless if you can only use it for macOS. – TheFox Mar 16 '18 at 18:03
-
@TheFox, yes, but your configuration files DO use a fixed host: whatever is set in ENV. :) This config is equivalent to the (more nimble?) solution by spinus above. I mean, I see what you're saying. – allanberry Mar 17 '18 at 13:20
-
2`host.docker.internal` [does work on Docker for Windows](https://docs.docker.com/docker-for-windows/networking/#there-is-no-docker0-bridge-on-windows) too, at least at the time of writing this comment. – joanlofe Jun 04 '19 at 08:27
-
4
-
-
2This absolutely does not work. host.docker.internal doesn't resolve to anything. This is far too complex to set up and does not work as documented. Docker version 20.10.5. – Triynko Apr 26 '21 at 04:16
-
5`host.docker.internal` worked for me (Windows 10, WSL2 Ubuntu 20.04, Laravel Sail) – Andrew P. Jul 14 '21 at 07:59
-
-
According to the [docs](https://docs.docker.com/desktop/networking/#per-container-ip-addressing-is-not-possible) linked above: "...connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. **This is for development purpose and does not work in a production environment outside of Docker Desktop.**" (Emphasis added.) So the reason some people see it and others don't is because it's only available for development purposes and doesn't work on prod. So, this goes right back to what TheFox said above. So much for build it once, run it everywhere – Richard Marskell - Drackir Mar 03 '23 at 22:03
Update: On Docker for Mac, as of version 18.03, you can use host.docker.internal as the host's IP. See aljabear's answer. For prior versions of Docker for Mac the following answer may still be useful:
On Docker for Mac the docker0
bridge does not exist, so other answers here may not work. All outgoing traffic however, is routed through your parent host, so as long as you try to connect to an IP it recognizes as itself (and the docker container doesn't think is itself) you should be able to connect. For example if you run this from the parent machine run:
ipconfig getifaddr en0
This should show you the IP of your Mac on its current network and your docker container should be able to connect to this address as well. This is of course a pain if this IP address ever changes, but you can add a custom loopback IP to your Mac that the container doesn't think is itself by doing something like this on the parent machine:
sudo ifconfig lo0 alias 192.168.46.49
You can then test the connection from within the docker container with telnet. In my case I wanted to connect to a remote xdebug server:
telnet 192.168.46.49 9000
Now when traffic comes into your Mac addressed for 192.168.46.49 (and all the traffic leaving your container does go through your Mac) your Mac will assume that IP is itself. When you are finish using this IP, you can remove the loopback alias like this:
sudo ifconfig lo0 -alias 192.168.46.49
One thing to be careful about is that the docker container won't send traffic to the parent host if it thinks the traffic's destination is itself. So check the loopback interface inside the container if you have trouble:
sudo ip addr show lo
In my case, this showed inet 127.0.0.1/8
which means I couldn't use any IPs in the 127.*
range. That's why I used 192.168.*
in the example above. Make sure the IP you use doesn't conflict with something on your own network.

- 7,325
- 6
- 42
- 71

- 16,771
- 8
- 64
- 65
-
3The usage of this hostname makes no sense since it doesn't work under Docker for Linux. Why did they not add it also for Linux? – TheFox Aug 28 '18 at 09:49
-
They are looking into it at this moment @TheFox: https://github.com/docker/libnetwork/pull/2348 – Ivo Pereira Dec 17 '19 at 12:51
-
AFAIK, in the case of Docker for Linux (standard distribution), the IP address of the host will always be 172.17.0.1
(on the main network of docker, see comments to learn more).
The easiest way to get it is via ifconfig
(interface docker0) from the host:
ifconfig
From inside a docker, the following command from a docker: ip -4 route show default | cut -d" " -f3
You can run it quickly in a docker with the following command line:
# 1. Run an ubuntu docker
# 2. Updates dependencies (quietly)
# 3. Install ip package (quietly)
# 4. Shows (nicely) the ip of the host
# 5. Removes the docker (thanks to `--rm` arg)
docker run -it --rm ubuntu:22.10 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null 2> /dev/null && ip -4 route show default | cut -d' ' -f3"

- 2,715
- 1
- 20
- 34
-
21This is true of containers attached to the `docker0` default bridge interface. It is not true of containers stood up using Docker Compose, which will not live on the default bridge interface. `docker network ls` and `docker network inspect
` can help you figure out what that IP will be. – Carl Patenaude Poulin Sep 22 '20 at 13:21 -
2Thanks for the instructions. Btw I'm on linux and I expected 172.17.0.1, in fact I'm checking a container and it haves 172.23.0.1. May the number of running containers affect how the host machine is mapped by incrementing the ip number ? – funder7 Oct 29 '20 at 12:04
-
1@funder7 It actually depends on what network you use inside docker. You can access networks with `docker network ls`, and if you didn't define any network, just know that docker-compose automatically defined virtual networks inside docker (that you can also list). – Nek Oct 29 '20 at 15:45
-
@Nek probably it was my fault, I was looking at the container's internal ip, while my docker0 network interface is 172.17.0.1, anyway I used docker.host.internal which now supports linux. Thanks for the command though, I will give it a try! – funder7 Oct 30 '20 at 09:48
-
For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.
curl http://169.254.169.254/latest/meta-data/local-ipv4
For example:
$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238
$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238

- 2,443
- 1
- 21
- 17
-
This is a super convenient method for those using AWS. I use this to configure Consul agents' client and bind addresses. It's ideal when you're in situations where you can't use host networking (like deploying containers in Elastic Beanstalk and ECS). – Richard Clayton Jul 11 '16 at 20:41
-
This is a lifesaver, thanks. I was having trouble figuring out how to handle communication between containers in my ECS cluster. – Brennan Sep 08 '16 at 06:35
-
On Phusion basimage (based on ubuntu), I had to change your command a little: `ifconfig eth0 | grep -oP 'inet \K\S+'` – Jean Claveau Jan 26 '20 at 14:56
-
-
for fargate you'll have to search for "IPv4Addresses" in the json response of http://169.254.170.2/v2/metadata/ – Jan 11 '21 at 10:54
-
Similarly in GCP: curl -s -H 'Metadata-Flavor: Google' http://metadata/computeMetadata/v1/instance/network-interfaces/0/ip for the first network interface – Rondo Aug 08 '22 at 21:47
docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'
It's possible to retrieve it using docker network inspect

- 459
- 4
- 11
-
4Best answer so far considering that it doesn't rely on any binary being present in a container. – Francesco Casula Aug 18 '21 at 13:21
The only way is passing the host information as environment when you create a container
run --env <key>=<value>

- 8,356
- 19
- 50
- 61

- 530
- 4
- 7
-
22More specifically, the bridge IP address can be passed in using a command line option like: `-e "DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+')"` (using the accepted answer from http://unix.stackexchange.com/questions/87468/is-there-an-easy-way-to-programmatically-extract-ip-address) – ncoghlan Sep 17 '15 at 08:04
-
8
The --add-host
could be a more cleaner solution (but without the port part, only the host can be handled with this solution). So, in your docker run
command, do something like:
docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [my container]
-
I said "made for this" when someone else wanted an entry in /etc/hosts; in this question it isn't really true. Also OP asked for "host and portmaps" and you have only covered the host. – Bryan Jan 18 '15 at 14:50
-
Ok. I was a bit confused as the accepted solution only covers the host part also. And I think your solution is superior to the one of spinus. – Augunrik Jan 19 '15 at 17:07
-
this doesn't work if you want to use dind - docker-in-docker. Inner docker will have different ip – noisy Aug 27 '15 at 12:55
The standard best practice for most apps looking to do this automatically is: you don't. Instead you have the person running the container inject an external hostname/ip address as configuration, e.g. as an environment variable or config file. Allowing the user to inject this gives you the most portable design.
Why would this be so difficult? Because containers will, by design, isolate the application from the host environment. The network is namespaced to just that container by default, and details of the host are protected from the process running inside the container which may not be fully trusted.
There are different options depending on your specific situation:
If your container is running with host networking, then you can look at the routing table on the host directly to see the default route out. From this question the following works for me e.g.:
ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'
An example showing this with host networking in a container looks like:
docker run --rm --net host busybox /bin/sh -c \
"ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'"
For current versions of Docker Desktop, they injected a DNS entry into the embedded VM:
getent hosts host.docker.internal | awk '{print $1}'
With the 20.10 release, the host.docker.internal
alias can also work on Linux if you run your containers with an extra option:
docker run --add-host host.docker.internal:host-gateway ...
If you are running in a cloud environment, you can check the metadata service from the cloud provider, e.g. the AWS one:
curl http://169.254.169.254/latest/meta-data/local-ipv4
If you want your external/internet address, you can query a remote service like:
curl ifconfig.co
Each of these have limitations and only work in specific scenarios. The most portable option is still to run your container with the IP address injected as a configuration, e.g. here's an option running the earlier ip
command on the host and injecting it as an environment variable:
export HOST_IP=$(ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p')
docker run --rm -e HOST_IP busybox printenv HOST_IP

- 231,797
- 42
- 475
- 450
-
worked for me -> ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p' – Vijay Dohare Dec 02 '22 at 14:22
-
TLDR for Mac and Windows
docker run -it --rm alpine nslookup host.docker.internal
... prints the host's IP address ...
nslookup: can't resolve '(null)': Name does not resolve
Name: host.docker.internal
Address 1: 192.168.65.2
Details
On Mac and Windows, you can use the special DNS name host.docker.internal
.
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

- 24,216
- 9
- 104
- 119
-
1Please don't add the [same answer to multiple questions](http://meta.stackexchange.com/questions/104227/is-it-acceptable-to-add-a-duplicate-answer-to-several-questions). Answer the best one and flag the rest as duplicates, once you earn enough reputation. If it is not a duplicate, tailor the post to the question and flag for undeletion. – Bhargav Rao Nov 07 '19 at 02:45
If you want real IP
address (not a bridge IP
) on Windows
and you have docker 18.03
(or more recent) do the following:
Run bash on container from host where image name is nginx
(works on Alpine Linux distribution
):
docker run -it nginx /bin/ash
Then run inside container
/ # nslookup host.docker.internal
Name: host.docker.internal
Address 1: 192.168.65.2
192.168.65.2
is the host's IP - not the bridge IP like in spinus
accepted answer.
I am using here host.docker.internal:
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker for Windows.

- 1,978
- 1
- 19
- 33
-
3I tried you solution and it seems that nslookup command cannot be found – Sergiy Dec 11 '18 at 12:40
-
@Sergey Is your image based on `Alpine Linux` ? If not then check equivalent for your specific `linux distribution`. – Kamil Witkowski Dec 11 '18 at 14:47
-
-
1Ok - if you are on windows, then i switched to `linux containers` and i am not using `windows containers`.You can do that by right clicking the `docker icon` and selecting `Switch to Linux containers`. I think that could be important when you are downloading image. If you had `windows container` check if deleting old `nginx` image and downloading it again will get you an other container. If it still won't work for you - than you can try to install `nslookup` in the `ash`. – Kamil Witkowski Dec 13 '18 at 09:04
-
If you can't do nslookup, just do ping. It'll show the resolved IP. For me this answer works, and I'm just using this hostname (`host.docker.internal`) from inside the container – Dmitry Minkovsky May 22 '19 at 20:22
-
I think that you do. You are missing the `ping` command to be exact. Try installing it, or use another command (for example `nslookup`). – Kamil Witkowski May 24 '19 at 12:49
-
Got the same IP as a result and I'm pretty sure my host's IP isn't 192.168.65.x, so I doubt this is the host's official public IP, but some internal local-only IP of host. – Thomas Urban Apr 25 '22 at 23:00
In linux you can run
HOST_IP=`hostname -I | awk '{print $1}'`
In macOS your host machine is not the Docker host. Docker will install it's host OS in VirtualBox.
HOST_IP=`docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'`

- 1,560
- 13
- 27
-
3
-
2mandoc of `hostname -I` warns to not "make any assumptions about the order of the output." – cannot_mutably_borrow Jul 21 '19 at 05:13
I have Ubuntu 16.03. For me
docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [image]
does NOT work (wrong ip was generating)
My working solution was that:
docker run --add-host dockerhost:`docker network inspect --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [image]

- 501
- 1
- 6
- 13
Docker for Mac I want to connect from a container to a service on the host
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.
The gateway is also reachable as gateway.docker.internal. https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds

- 69
- 2
- 5
If you enabled the docker remote API (via -H
tcp://0.0.0.0:4243
for instance) and know the host machine's hostname or IP address this can be done with a lot of bash.
Within my container's user's bashrc
:
export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
curl -s http://$hostIP:4243/containers/$containerID/json |
node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)
The second line grabs the container ID from your local /proc/self/cgroup
file.
Third line curls out to the host machine (assuming you're using 4243 as docker's port) then uses node to parse the returned JSON for the DESIRED_PORT
.

- 14,080
- 5
- 48
- 107

- 197
- 4
- 2
-
This only applies when you use port forwarding. Indeed `HostPort` can be useful information here, unfortunately the `HostIp` might be `0.0.0.0` – Arnout Engelen Jan 06 '17 at 13:48
-
Your solution to find the host's IP is relying on knowing the host's hostname _or IP_? – Thomas Urban Apr 25 '22 at 23:02
My solution:
docker run --net=host
then in docker container:
hostname -I | awk '{print $1}'

- 696
- 1
- 6
- 20
Here is another option for those running Docker in AWS. This option avoids having using apk to add the curl package and saves the precious 7mb of space. Use the built-in wget (part of the monolithic BusyBox binary):
wget -q -O - http://169.254.169.254/latest/meta-data/local-ipv4

- 57
- 3
This is a minimalistic implementation in Node.js for who is running the host on AWS EC2 instances, using the afore mentioned EC2 Metadata instance
const cp = require('child_process');
const ec2 = function (callback) {
const URL = 'http://169.254.169.254/latest/meta-data/local-ipv4';
// we make it silent and timeout to 1 sec
const args = [URL, '-s', '--max-time', '1'];
const opts = {};
cp.execFile('curl', args, opts, (error, stdout) => {
if (error) return callback(new Error('ec2 ip error'));
else return callback(null, stdout);
})
.on('error', (error) => callback(new Error('ec2 ip error')));
}//ec2
and used as
ec2(function(err, ip) {
if(err) console.log(err)
else console.log(ip);
})

- 9,564
- 146
- 81
- 122

- 15,724
- 11
- 102
- 146
Try this:
docker run --rm -i --net=host alpine ifconfig

- 9,564
- 146
- 81
- 122

- 101
- 4
So... if you are running your containers using a Rancher server, Rancher v1.6 (not sure if 2.0 has this) containers have access to http://rancher-metadata/ which has a lot of useful information.
From inside the container the IP address can be found here:
curl http://rancher-metadata/latest/self/host/agent_ip
For more details see: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/

- 362
- 2
- 7
If you are running a Windows container on a Service Fabric cluster, the host's IP address is available via the environment variable Fabric_NodeIPOrFQDN
. Service Fabric environment variables

- 6,548
- 1
- 32
- 41
Here is how I do it. In this case, it adds a hosts entry into /etc/hosts within the docker image pointing taurus-host to my local machine IP: :
TAURUS_HOST=`ipconfig getifaddr en0`
docker run -it --rm -e MY_ENVIRONMENT='local' --add-host "taurus-host:${TAURUS_HOST}" ...
Then, from within Docker container, script can use host name taurus-host to get out to my local machine which hosts the docker container.

- 28,471
- 61
- 196
- 289
Maybe the container I've created is useful as well https://github.com/qoomon/docker-host
You can simply use container name dns to access host system e.g. curl http://dockerhost:9200, so no need to hassle with any IP address.

- 4,549
- 1
- 21
- 27
The solution I use is based on a "server" that returns the external address of the Docker host when it receives a http request.
On the "server":
1) Start jwilder/nginx-proxy
# docker run -d -p <external server port>:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
2) Start ipify container
# docker run -e VIRTUAL_HOST=<external server name/address> --detach --name ipify osixia/ipify-api:0.1.0
Now when a container sends a http request to the server, e.g.
# curl http://<external server name/address>:<external server port>
the IP address of the Docker host is returned by ipify via http header "X-Forwarded-For"
Example (ipify server has name "ipify.example.com" and runs on port 80, docker host has IP 10.20.30.40):
# docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
# docker run -e VIRTUAL_HOST=ipify.example.com --detach --name ipify osixia/ipify-api:0.1.0
Inside the container you can now call:
# curl http://ipify.example.com
10.20.30.40

- 1
- 1
On Ubuntu, hostname
command can be used with the following options:
-i
,--ip-address
addresses for the host name-I
,--all-ip-addresses
all addresses for the host
For example:
$ hostname -i
172.17.0.2
To assign to the variable, the following one-liner can be used:
IP=$(hostname -i)

- 155,785
- 88
- 678
- 743
-
3This will give you the IP address of the Docker container, not of the host – Mario Camou Feb 28 '20 at 16:20
Another approach is based on traceroute
and it's working on a Linux host for me, e.g. in a container based on Alpine:
traceroute -n 8.8.8.8 -m 4 -w 1 | awk '$1~/\d/&&$2!~/^172\./{print$2}' | head -1
It takes a moment, but lists the first hop's IP that does not start with 172. If there is no successful response, try increasing the limit on the tested hops using -m 4
argument.

- 4,649
- 26
- 32
With https://docs.docker.com/machine/install-machine/
a) $ docker-machine ip
b) Get the IP address of one or more machines.
$ docker-machine ip host_name
$ docker-machine ip host_name1 host_name2

- 312,688
- 75
- 539
- 559

- 7,515
- 3
- 24
- 21
-
10This retrieves the IP of the virtual machine that runs the docker containers, not the IP of the host that the containers run in. – Spencer Williams Nov 29 '16 at 18:59
-
2This only applies to docker that's running on docker-machine. The new docker for mac doesn't run on docker-machine. – thomas.han Aug 10 '17 at 05:04