Skip to content

Instantly share code, notes, and snippets.

@jamshid
Last active June 18, 2023 18:05
Show Gist options
  • Save jamshid/7934004 to your computer and use it in GitHub Desktop.
Save jamshid/7934004 to your computer and use it in GitHub Desktop.
Docker environment hack, to put the names of running containers in /etc/hosts
#!/bin/bash
# An alternative to "links", run this script after starting or stopping any
# container. It's a hack to update the host machine (vagrant) /etc/hosts with
# the current active docker containers and tell dnsmasq to refresh.
#
# Then start each machine with "-dns ${DOCKER_HOST_IP}", e.g.
# $ docker run -d -name mycontainer1 -dns 10.0.3.1 MYPRODUCT
# You can't seem to set the DNS during "docker build".
#
# Diagnostic command to run in host or while logged into containers:
# # dig @10.0.3.1 mycontainer1
#
cd ${0%/*}
function dip() { docker inspect $1 | grep IPAddress | cut -d '"' -f 4 ; }
cat /etc/hosts | grep -v '#DOCKER-DELETE-ME' > /etc/hosts.docker.tmp
RESULT="$?"
if [ ${RESULT} = 0 ]; then
echo "Checking for running docker containers..."
else
echo "Error modifying /etc/hosts, try running with sudo."
exit 1
fi
echo "# Below are the docker hosts running at $(date). #DOCKER-DELETE-ME" >> /etc/hosts.docker.tmp
docker ps | awk '{print $1}' | while read CONTAINERID
do
IP=$(dip ${CONTAINERID})
if [ -n "${IP}" ] ; then
NAME=$(docker inspect ${CONTAINERID} | grep Name | cut -d '"' -f 4 | sed 's#^/##g')
echo "${IP} ${NAME} #DOCKER-DELETE-ME" >> /etc/hosts.docker.tmp
fi
done
mv -f /etc/hosts.docker.tmp /etc/hosts
killall -HUP dnsmasq
echo 'Updated /etc/hosts with current ("docker ps") entries...'
tail -10 /etc/hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment