Skip to content

Instantly share code, notes, and snippets.

@gregor-j
Last active December 20, 2021 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregor-j/f836e8be27342fba1bdf5ab0a28a0e33 to your computer and use it in GitHub Desktop.
Save gregor-j/f836e8be27342fba1bdf5ab0a28a0e33 to your computer and use it in GitHub Desktop.
docker network containers in /etc/hosts format

Print a list of docker containers in hosts style

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.

Step 1 format

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)

Step 2 filter

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

Step 3 save

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.

Step 4 cleanup

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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment