It's not a problem to resolve a hostname or an alias inside a network of docker containers,
but there's currently no tool to export a /etc/hosts
style list of docker container IPs and their hostnames and aliases for your docker host.
Format the docker inspect
output in /etc/hosts
style.
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{range .Aliases}} {{.}}{{end}}{{end}} {{.Config.Hostname}}' $(docker ps -q)
Not all hostnames are desired, e.g. the ID based hostnames. Hostnames with TLD .test
are reasonable for testing.
I haven't found a way to do that in the --format
part.
Let's use some shell power (sorry windows, I have a different understanding of power):
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{range .Aliases}} {{.}}{{end}}{{end}} {{.Config.Hostname}}' $(docker ps -q) | while read ip names; do echo -n "$ip"; for name in ${names}; do case "$name" in *.test) echo -n " $name";; esac; done; echo; done
The /etc/hosts
file is only writeable with root privileges. Docker gives those privileges without requiring a password.
Thank you, docker hipsters for building this great security leak right into the very heart of your design.
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{range .Aliases}} {{.}}{{end}}{{end}} {{.Config.Hostname}}' $(docker ps -q) | while read ip names; do echo -n "$ip"; for name in ${names}; do case "$name" in *.test) echo -n " $name";; esac; done; echo; done | docker run --rm -i -v /etc/hosts:/tmp/h busybox tee -a /tmp/h
This 1-liner extracts, filters, and writes all running docker containers into your docker hosts /etc/hosts
file. You can now access all their ports via their proper hostnames instead of port-forwarding single ports.
We add hosts, we remove hosts. All hostnames had the TLD .test
.
docker run --rm -v /etc/hosts:/tmp/h busybox sh -c 'sed -E "/.*\.test/d" /tmp/h | awk "NF" | tee /tmp/g; cat /tmp/g > /tmp/h'