Skip to content

Instantly share code, notes, and snippets.

@clockworkgeek
Last active March 28, 2016 16:46
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 clockworkgeek/ab639c9fe6fbb442d8e5 to your computer and use it in GitHub Desktop.
Save clockworkgeek/ab639c9fe6fbb442d8e5 to your computer and use it in GitHub Desktop.
A service script that waits on "docker events" and adds new containers and their host names to "dnsmasq"
#!/bin/bash
# put me in /usr/bin/auto-dev-hosts
HOSTSDIR=/tmp/auto-dev-hosts
# create dir
install -d "$HOSTSDIR"
RELOADFLAG=/tmp/auto-dev-hosts.flag
SCRIPTNAME=$(basename "$0")
function add_hosts {
for CONTAINER in "$@"
do
# write temporary hosts file
docker inspect -f '{{$c := .Config}}{{range .NetworkSettings.Networks}}{{if .IPAddress}}{{.IPAddress}}{{if $d := $c.Domainname}} {{$c.Hostname}}.{{$d}}{{end}} {{$c.Hostname}}{{end}}{{end}}' "$CONTAINER" > $HOSTSDIR/$CONTAINER
done
}
# reload dnsmasq if root
# delay for 3 seconds in case there are more edits coming
function reload_dnsmasq {
if (( EUID == 0 ))
then
(
sleep 3
if [[ -f $RELOADFLAG ]]
then
echo "Reloading dnsmasq..."
pkill -x -1 dnsmasq
fi
rm -f $RELOADFLAG
)&
touch $RELOADFLAG
fi
}
function clean_up {
FILES=$(shopt -s nullglob; echo ${HOSTSDIR}/*)
if (( ${#FILES} ))
then
rm "${FILES[@]}"
reload_dnsmasq
fi
rmdir "$HOSTSDIR"
exit
}
trap clean_up SIGHUP SIGINT SIGTERM
RUNNING=($(docker ps -q --no-trunc))
if (( ${#RUNNING} ))
then
docker inspect -f '{{.Name}} was found at{{range .NetworkSettings.Networks}} {{.IPAddress}}{{end}}' "${RUNNING[@]}"
add_hosts "${RUNNING[@]}"
reload_dnsmasq
fi
docker events -f "type=container" -f "event=start" -f "event=stop" -f "event=die" | while read -a line
do
EVENT=${line[2]}
CONTAINER=${line[3]}
case $EVENT in
start)
docker inspect -f '{{$Name := .Name}}{{range .NetworkSettings.Networks}}{{$Name}} has started at {{.IPAddress}}{{end}}' "$CONTAINER"
add_hosts "$CONTAINER"
reload_dnsmasq
;;
stop|die)
docker inspect -f '{{.Name}} has stopped.' "$CONTAINER"
if [[ -s "$HOSTSDIR/$CONTAINER" ]]
then
rm "$HOSTSDIR/$CONTAINER"
reload_dnsmasq
else
rm -f "$HOSTSDIR/$CONTAINER"
fi
;;
esac
done
clean_up
# put me in /etc/NetworkManager/dnsmasq.d/auto-dev-hosts
hostsdir=/tmp/auto-dev-hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment