Skip to content

Instantly share code, notes, and snippets.

@martin31821
Forked from jamshid/update-hosts.sh
Created May 30, 2018 21:47
Show Gist options
  • Save martin31821/4258005884f16bdd349a0d25f5efb29f to your computer and use it in GitHub Desktop.
Save martin31821/4258005884f16bdd349a0d25f5efb29f 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 -q | while read CONTAINERID
do
IP=$(docker inspect ${CONTAINERID} | jq -r '.[0].NetworkSettings.Networks as $in | $in | keys[] | $in[.].IPAddress')
if [ -n "${IP}" ] ; then
NAME=$(docker inspect ${CONTAINERID} | jq -r '.[0].Name' | cut -c 2-)
for i in ${IP}; do
echo "${i} ${NAME} #DOCKER-DELETE-ME" >> /etc/hosts.docker.tmp
done
fi
done
mv -f /etc/hosts.docker.tmp /etc/hosts
echo 'Updated /etc/hosts with current ("docker ps") entries...'
tail -10 /etc/hosts
@martin31821
Copy link
Author

Updated to docker 18.05, should work with older versions as well.
Uses jq to ease up processing and speed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment