12

I need to know the hostnames (or ip addresses) of some container running on the same machine. As I already commented here (but with no answer yet), I use docker-compose. The documentation says, compose will automatically create a hostname entry for all container defined in the same docker-compose.yml file:

Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

But I can't see any host entry via docker exec -it my_container tail -20 /etc/hosts. I also tried to add links to my container, but nothing changed.

Community
  • 1
  • 1
Munchkin
  • 4,528
  • 7
  • 45
  • 93

1 Answers1

16

Docker 1.10 introduced some new networking features which include an internal DNS server where host lookups are done.

On the default bridge network (docker0), lookups continue to function via /etc/hosts as they use to. /etc/resolv.conf will point to your hosts resolvers.

On a user defined network, Docker will use the internal DNS server. /etc/resolv.conf will have an internal IP address for the Docker DNS server. This setup allows bridge, custom and overlay networks to work in a similar fashion. So an overlay network on swarm will populate host data from across the swarm like a local bridge network would.

The "legacy" setup was maintained so the new networking features could be introduced without impacting existing setups.

Discovery

The DNS resolver is able to provide IP's for a docker compose service via the name of that service.

For example, with a web and db service defined, and the db service scaled to 3, all db instances will resolve:

$ docker-compose run --rm web nslookup db

Name:      db
Address 1: 172.22.0.4 composenetworks_db_2.composenetworks_mynet
Address 2: 172.22.0.5 composenetworks_db_3.composenetworks_mynet
Address 3: 172.22.0.3 composenetworks_db_1.composenetworks_mynet
Matt
  • 68,711
  • 7
  • 155
  • 158
  • Do you know how to get the names of the available services running from within a container? `docker-compose config --service` does this from the host but not within the container, and `cat /etc/resolv.conf` just shows `nameserver 127.0.0.11 options ndots:0` – user1717828 Oct 09 '18 at 13:20
  • 2
    You may want to run that with `--rm` or end up with a bunch of containers you don't want sticking around – keyboardSmasher May 27 '19 at 15:30