Get docker container IP by alias - docker

From the host environment, is there a way to get the container and its properties, at least to get its IP(s) addresses, by querying using its alias?
For clarity, I'm referring to the actual alias you can give to containers on specific networks, see here
Currently my solution so far is iterating over all containers through the rest API and see if the alias matches what I'm looking for. It's obvious this is not ideal as this does not scale well in the case there are many containers on the host.
Ideally I'd want to just send a DNS request to docker's embedded dns server, but this does not seem possible. See this question/answer for more info
Does anyone know of a better solution?
/update
since an alias is tied to a network, it's expected that the to-be queried alias is accompanied with its network name, e.g., 'container-alias.network-name'. So we'd have to enumerate over the containers in a single network, but even this does not scale well if there are many containers in a single network.
Mind you, that getting all containers filtered by network name is possible in the docker api, allowing for a single REST call to the api. However, even though the 'Alias' key is in the REST result, it never holds any values. (this might be a bug, I'm not sure.) You have to GET for a specific container, i.e., GET /v1.24/containers/container-uuid/json before you can see its aliases.

There's almost certainly a neater way to do this, maybe even entirely using docker inspect, but if you have jq available you can try something like:
docker inspect -f '{{json .NetworkSettings.Networks}}' <container name/ID> | \
jq '.[] | select(.Aliases[] | contains("<alias on network>")) | .IPAddress'

Remember that most of these details aren't useful outside of Docker space; except on one very specific configuration (on the same native-Linux host as the container) you can't directly access the container-specific IP addresses.
If you can run docker commands you can start containers, so you can get indirect access to the Docker DNS system. For example, let's start a container with an alias on a non-default network:
docker network create testnet
docker run \
--net testnet \
--name sleep \
--network-alias zzz \
-d \
busybox \
sleep 600
Now we can run another container on that same network and start making DNS queries. We can get the Docker-internal IP address of the zzz alias:
$ docker run --net testnet --rm giantswarm/tiny-tools dig +short zzz
172.18.0.2
Then we can reverse-resolve that address:
$ docker run --net testnet --rm giantswarm/tiny-tools dig +short -x 172.18.0.2
sleep.testnet.
That canonical name is the container name and network, and if you need to probe deeper, you can now docker inspect sleep.

I think you should know what you are doing by reading the docker ref
And then, caress docker simple than ever by just run the following
cat << EOF >> /etc/bash.bashrc
function docker(){
[[ "ip" == "$1" ]] && /usr/bin/docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $2 || /usr/bin/docker $#
}
EOF
source /etc/bash.bashrc
docker ip $INSTANCE_ID

Related

docker-compose hostname and local resolution

When creating docker containers with a docker-compose file which specifies hostname (hostname:) and ip addresses (ipv4_address:), I would like the local computer (the computer that runs the docker daemon service, aka my laptop) to be able to resolve those hostnames, without the need of (too much) manual intervention. I.e. if the container is a webserver service with hostname my_webserver, I would like that my_werbserver resolve to the IP address I assigned to that container.
What's the best way to achieve that? Anything better than maintaining /etc/hosts on my laptop manually?
As #Kārlis Ābele mentioned, I don't think you can do what you need without additional services. One solution would be to run dnsmasq in a docker container in the same network as the other docker containers. See Make the internal DNS server available from the host
docker run -d --name dns -p 53:53 -p 53:53/udp --network docker_network andyshinn/dnsmasq:2.76 -k -d
Check that it works using localhost as DNS
nslookup bar localhost
Optionally setup localhost as DNS server. On Ubutu 18.04 for example, edit /etc/resolvconf/resolv.conf.d/head.
nameserver localhost
Restart the resolvconf service.
sudo service resolvconf restart
Now you should be able to ping the containers by name.
EDITED:
An alternative solution (based on #Kārlis Ābele answer) is to listen to docker events and update /etc/hosts. A barebones implementation:
#!/usr/bin/env bash
while IFS= read -r line; do
container_id=$(echo ${line}| sed -En 's/.*create (.*) \(.*$/\1 /p')
container_name=$(echo ${line}| sed -En 's/.*name=(.*)\)$/\1 /p')
ip_addr=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${container_id})
echo ${ip_addr} ${container_name} >> /etc/hosts
done < <(docker events --filter 'event=create')
Well it seems like something that won't be possible without some custom service that is listening for events on Docker daemon...
How I would do this, is write a simple service that is listening for Docker events (https://docs.docker.com/engine/reference/commandline/events/) and updates /etc/hosts file accordingly.
Other than that, without manually updating hosts file I don't think there are other options though.

Assigning a local IP to docker containers

Is there a way to have docker automatically give it’s containers a local IP address that you can reach with it’s ports exposed?
For example, LXC has ways to do this.
lxc-create -t ubuntu -n myname
lxc-start -n myname -d
Which will then assign a local IP which you can see via lxc-ls if you have a bridge configured:
lxc-ls -f
This is super convenient for throwing up a bunch of containers for testing out deployment/configuration management like ansible.
Is it possible to do something similar in docker without much headache? I come from using LXC and I’m not familiar with the networking modes.
LXC and Docker are very similar. When LXC is installed, a random subnet is picked for configuring the IP addresses of bridge and the containers attached to it. With Docker, the default subnet is 172.17.0.0/16, which can be customized if needed. Every container stared (unless using host network or network of another container) using docker run command are assigned an IP address from the above subnet.
docker ps lists all the containers running but unfortunately it doesn't show the IP addresses.
Looks like a small trick can show the IP addresses: (based on this post)
docker ps -q | xargs docker inspect --format '{{ .Id }} - {{ .Name }} - {{ .NetworkSettings.IPAddress }}'
Also you can expose the ports using the -p option of docker run command.
Example:
docker run -itd -p 8080:80 nginx
This starts the container on the docker bridge and also exposes the nginx on the host network via port 8080.
from_host_running_container# curl http://172.17.x.y
from_not_the_host_running_container # curl http://${HOST_IP}:8080

Docker. Add dynamic host ip to env var on container

I have a very special scenario. A virtual machine containing some docker containers. One of this containers needs to know the host ip. The problem is if I pass the host ip on container build or using -e on docker run command, it remains "static" (always the same, the one of that moment) on the container.
That vm can be on a laptop and the laptop is moving from different networks and the vm host ip can be different each reboot.
This special container has the --restart=always and is not built or "docker run" again... only once. And as I said, I need the host's ip on each reboot to configure the service inside the container on it's entrypoint because the container has a bind dns server which must load a zone with some dns entries that must be pointing to itself (the host's ip). An environment var would be great if possible. These are my data:
The "normal" lauch
The end of my Dockerfile:
....
....
ENTRYPOINT ["/etc/bind/entrypoint.sh"]
CMD ["/usr/sbin/named", "-g", "-c", "/etc/bind/named.conf", "-u", "bind"]
Entrypoint file (the regex works fine if the var could have the right value):
#!/bin/bash
sed -ri "s/IN A.*/IN A $HOSTIP/" /etc/bind/db.my.zone
exec "$#"
Docker run cmd:
docker run --name myContainer -d --restart=always -p 53:53 -p 53:53/udp myImage
What I tried:
I guess the entrypoint is ok and shouldn't be modified if I can provide to it a var with the right value.
If I put a -e on docker run command, it is "hardcoded" forever with the same ip always even if the host is on different networks:
docker run -e HOSTIP=$(ifconfig eth0 | grep netmask | awk '{print $2}') --name myContainer \
-d --restart=always -p 53:53 -p 53:53/udp myImage
I tried unsuccessfully also modifying the CMD on Dockerfile:
CMD (export HOSTIP=$(ifconfig eth0 | grep netmask | awk '{print $2}'));/usr/sbin/named -g -c /etc/bind/named.conf -u bind
Is possible to achieve something like this? Thanks.
There is the file /proc/net/tcp on the host machine that shows all the opened sockets. In particular, the second column is the local_address of the host interface.
The values in this column are store as little-endian four-byte hexadecimal numbers. To convert these to IP addresses take a look here
Thus when starting you container, you can mount this file from the host onto the container -v /proc/net/tcp:/host-tcp and read the host ip addresses which will be constantly reflected in this file.
I finally solved it. Thank you #yamenk for your answer, it gave me the idea, upvoting.
Finally what I did:
I created a simple script on host which is getting host ip and writting it into another file.
I set that script to be launched on every host boot before docker start.
I mapped the file with the ip into the container using -v on docker run command.
I set my entrypoint to get the ip from that file containing the ip and modifying with sed the needed container config files
Everything working! if I boot the vm (the host machine) on another different network, it gets the ip and the container is able to reconfigure itself before starting with the new ip.

Communicate to Docker host from Docker container

I’m experimenting with docker networking, and I can’t seem to find a way to accomplish the following:
Start a simple netcat server in the host:
nc -l -p 5555
and then communicate to this server from within a docker container, e.g.
# grab the docker network interface ip
hostip=$(ip route | awk '/docker0/ { print $NF }')
# pass in the docker network interface as a host and try a curl command
docker run --add-host=docker:"${hostip}" --rm -it hiromasaono/curl curl docker:5555
The curl request just hangs and the host netcat server does not receive a request.
If I instead start docker with --net=host option, it works:
docker run --net=host --rm -it hiromasaono/curl curl 127.0.0.1:5555
and the netcat server receives
GET / HTTP/1.1
User-Agent: curl/7.35.0
Host: 127.0.0.1:5555
Accept: */*
How can I communicate to the simple host netcat server from within the docker container without using --net=host (the default is --net=bridge)?
(fyi: I'm running docker server/client 1.11.2)
Potentailly Relevant Resources I've Studied in search of an answer:
Document how to connect to docker host from container (github issue)
How to connect to Docker host from container (github issue)
Allow Docker Container to Connect to a Local Postgres DB
Docker Container Networking Documentation
As far as I understand, based on two comments[1][2], the following unofficial hack seems to be working for me as of today (2016.10.27):
In the Dockerfile for the app which needs to connect to the Docker host, I added the following lines:
...
# netstat
RUN apt-get update && apt-get install net-tools -y
...
CMD (netstat -nr | grep '^0\.0\.0\.0' | awk '{print $2" dockerhost"}' >> /etc/hosts) && \
...old CMD line...
...
This seems to make the Docker host available to me from within the container as dockerhost.
Note to future readers: see also https://github.com/docker/docker/issues/23177 — as of writing, this issue is still open, so there's a non-zero chance it may become official at some point in future and supersede any workarounds; though it may also become closed and dismissed as happened to its various predecessors.
There are a couple of things you need to look into, in order to solve this problem.
Netcat must listen on all interfaces (or at least on the interface Docker clients can connect to). Not on localhost.
After you run netcat -l -p 5555 if in another terminal you run netstat -a -l -n | grep 5555 you should see 0.0.0.0:5555 or *:5555. If instead you see 127.0.0.1:5555 then it won't work and you need to fix this problem first before looking into Docker.
Docker must be able to ping the docker host and it must not resolve to 127.0.0.1 . Try docker run --net=host --rm -it hiromasaono/curl ping docker. If you see it's pinging 127.0.0.1 then your configuration is wrong and you need to fix this line: hostip=$(ip route | awk '/docker0/ { print $NF }') . If it's not 127.0.0.1 but the pings don't succeed then your network setup is wrong or the hostip is wrong.

How to get the IP address of the docker host from inside a docker container [duplicate]

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(41 answers)
Closed 10 months ago.
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.
/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.
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
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.
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.04 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null && ip -4 route show default | cut -d' ' -f3"
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
The only way is passing the host information as environment when you create a container
run --env <key>=<value>
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]
(From https://stackoverflow.com/a/26864854/127400 )
docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'
It's possible to retrieve it using docker network inspect
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
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.
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.
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'/.$//'`
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]
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
If you enabled the docker remote API (via -Htcp://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.
My solution:
docker run --net=host
then in docker container:
hostname -I | awk '{print $1}'
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
use hostname -I command on the terminal
Try this:
docker run --rm -i --net=host alpine ifconfig
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/
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);
})
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
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.
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.
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
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)
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.
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

Resources