简体   繁体   中英

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. Ie 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?

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM