Skip to content

Instantly share code, notes, and snippets.

@hattwj
Last active August 22, 2022 16:29
Show Gist options
  • Save hattwj/6c64c2b4b100761df9c244d2256f4d51 to your computer and use it in GitHub Desktop.
Save hattwj/6c64c2b4b100761df9c244d2256f4d51 to your computer and use it in GitHub Desktop.
Quickly add hostname aliases for running docker-compose containers
#!/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