6

I would like to be able to get a list of all containers running on the same docker network from within a docker container. As the built in docker DNS can give me the IP addresses if I have the hostnames, it seems like it should be able to just give me a list of hostnames (maybe DNS cannot do this, I don't know).

Other approaches that I've thought of for getting a list of containers:

  • Bind mount the docker socket into the container and use docker ps. Not a great idea as far as security goes.
  • Use --link which I believe places entries in /etc/hosts. I could then read them from there, but this sort of defeats the purpose as I would have to already know the host names when I launched the container.

I'm looking to avoid using an external service discovery mechanism, but I would appreciate all suggestions for how to get a list of containers.

nathanielobrown
  • 992
  • 7
  • 15

1 Answers1

1

An easy way to achieve this would be running a one or more docker command(s) in the host, to get the information you need in a loop and store it in a known location (ex in bash)

while true; do echo `docker ps --format {{.ID}}` > /SOME/KNOWN/FILE; sleep 5; done

and then let the containers access this file, using volumes.

It is much safer than providing access to the docker socket, and you can improve it to provide all the information you need (ex json with name, ip, running time, etc).

Salem
  • 12,808
  • 4
  • 34
  • 54
  • [`docker events`](https://docs.docker.com/engine/reference/commandline/events/) might be useful here too if you want to limit the polling. – Matt Jan 30 '17 at 02:59
  • Mmm, I see. Not the answer I was looking for, but a clever solution. – nathanielobrown Feb 11 '17 at 20:08
  • Since I already have a shared redis cache, I make every container instance update a shared key (using already present redlock) on start up and shutdown. – Jeroen Visscher Sep 21 '22 at 12:51