Last active
August 22, 2022 16:29
-
-
Save hattwj/6c64c2b4b100761df9c244d2256f4d51 to your computer and use it in GitHub Desktop.
Quickly add hostname aliases for running docker-compose containers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Run this file on the host machine that is running dockerd | |
# It will allow you to access your docker containers via hostname aliases | |
# Remove old lines with suffix | |
sed -i -e "/#docker-temp/d" /etc/hosts | |
# Collect ip-addresses and hostnames of running docker-compose containers | |
ADDR=$(docker-compose ps -q | xargs --no-run-if-empty -I --- docker exec --- hostname -I| sed -e 's/ /-/') | |
NAMES=$(docker-compose ps -q|xargs --no-run-if-empty docker inspect -f '{{ .Name }}' | sed -e 's/\///' | sed -e 's/ /-/') | |
# Abort if containers aren't running | |
if [ -z "$ADDR" ]; then | |
echo no addresses | |
exit | |
fi | |
if [ -z "$NAMES" ]; then | |
echo no names | |
exit | |
fi | |
# Interleave addresses and hostnames, add suffix for easy removal later | |
LIST=$(paste <(echo "$ADDR") <(echo "$NAMES") --delimiters '-') | |
LIST=$(echo $LIST | sed -e "s/ /\n/g" | sed -e "s/-/ /g" | sed -e "s/$/ #docker-temp/") | |
# Add hostnames to /etc/hosts | |
bash -c "echo \"$LIST\" >> /etc/hosts" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment