Saturday, October 4, 2014

DDNS with Docker and nsupdate

Many robust and scalable solutions exist for monitoring docker containers and publish their IP addresses into some service discovery solution.  SkyDNS or consul.io are such examples.  However I wanted a simpler solution for the few containers I run on my home network server, so I put together the simplest service discovery mechanism possible.

Place the following file in /etc/cron.daily - this has been tested on Ubuntu 14.04:
#!/bin/bash

CONTAINERS=($(docker ps -q))    # fetch all containers
DOMAIN="example.com"
KEY="/etc/bind/rndc.key"
TTL="86400"                     # 1 day
TMPFILE="/tmp/dns_updates"

# prepare file
if [ -f $TMPFILE ]; then
  rm $TMPFILE
fi

for CONTAINER in ${CONTAINERS[@]}; do
  NAME=`docker inspect -f '{{.Name}}' $CONTAINER`
  NAME=${NAME#/} # remove leading / from container name
  IP=`docker inspect -f '{{.NetworkSettings.IPAddress}}' $CONTAINER`
  echo "update add $NAME.$DOMAIN $TTL A $IP" >> $TMPFILE
done
echo "send" >> $TMPFILE

nsupdate -k $KEY $TMPFILE
exit 0

The script be executed daily. It fetches all containers from docker and publishes their name+domain with their ip address to bind9 DNS server.

If start new containers, you can manually run the script again to update DNS.

Note: this script does not remove DNS names when you stop containers.