Docker Container Get IP Address from host interfaces

I am running docker on an Ubuntu 18.04 Server which has 3 physical network interfaces.
I have a container that hosts a website running in a custom network bridge.
I want this website to be able to display the IP Address of the devices physical network interfaces. These interfaces could be DHCP and can change at any time.

Any suggestions would be appreciated.

Pass them as environment variables to the container.

root@manager:~# hostname -I
10.0.2.15 172.28.128.3 172.17.0.1 172.18.0.1

You may want/need to be more selective on what IP addresses you actually pass.

root@manager:~# docker container run -it --env "MY_IPS=$(hostname -I)" alpine:latest sh
/ # echo $MY_IPS
10.0.2.15 172.28.128.3 172.17.0.1 172.18.0.1
/ # 

It looks like that will only get the IP address of the interfaces when the container is started… If the Interface address is changed the container will not get the new ip address.

You could use a docker bind mount on the application container and store the IP addresses in the bind mount source directory and then refresh them when they change. Your application could then retrieve them from there as often as you need it too.

root@manager:~# echo "My IPs are : $(hostname -I)" > my_ips.txt
root@manager:~# docker container run -it -p 80:80 --mount type=bind,source="$(pwd)",target=/my_ips alpine:latest sh
/ # cat my_ips/my_ips.txt
My IPs are : 10.0.2.15 172.28.128.3 172.17.0.1 172.18.0.1
/ #

That option would work for me. Is there not a way for the container to call ifconfig or something similar directly?

Not that I am aware of. The best option is for your application to have a “REST” API that could receive the updated IP addresses from.

Another possibility is to run docker inside your application docker container and then run a container on the docker node to display the IP addresses. You would have to pass the /var/run/docker.sock to your application container too via --volume /var/run/docker.sock:/var/run/docker.sock

Example:

root@manager:~# docker container run -it -p 80:80 --mount type=bind,source="$(pwd)",target=/my_ips --volume /var/run/docker.sock:/var/run/docker.sock ubuntu:latest sh

Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
38e2e6cd5626: Pull complete
705054bc3f5b: Pull complete
c7051e069564: Pull complete
7308e914506c: Pull complete
Digest: sha256:945039273a7b927869a07b375dc3148de16865de44dec8398672977e050a072e
Status: Downloaded newer image for ubuntu:latest

Now inside the container install Docker

# apt-get update -qq && apt-get install curl -y && curl --silent -SL https://get.docker.com/ | sh
--- left out the output of these commands ---

Then you can run a container on the docker host from the application container and display the IPs

# docker run -i --rm --network host ubuntu:latest hostname -I
10.0.2.15 172.28.128.3 172.17.0.1 172.18.0.1
1 Like