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