Skip to content

Instantly share code, notes, and snippets.

@mterrel
Last active August 14, 2020 03:35
Show Gist options
  • Save mterrel/51aa6e0eb4b74b7ce28376d234848f1e to your computer and use it in GitHub Desktop.
Save mterrel/51aa6e0eb4b74b7ce28376d234848f1e to your computer and use it in GitHub Desktop.
Docker DNS cache script
#!/usr/bin/env bash
: "${IMAGE:=andyshinn/dnsmasq:2.76}"
: "${NAME:=dnsmasq}"
: "${ADAPT_DNS_IP_FILE:=/tmp/adapt_dns_ip}"
# Get IP address for an interface, as visible from inside a container
# connected to the host network
interfaceIP() {
# Run a container and get ifconfig output from inside
# We need the ifconfig that will be visible from inside the dnsmaq
# container
docker run --rm --net=host busybox ifconfig "$1" 2>/dev/null | \
awk '/inet /{print(gensub(/^.*inet (addr:)?([0-9.]+)\s.*$/, "\\2", 1))}'
}
if docker inspect --type container "${NAME}" >& /dev/null ; then
if [ -f "${ADAPT_DNS_IP_FILE}" ]; then
# dnsmasq is already started
cat "${ADAPT_DNS_IP_FILE}"
exit 0
else
echo DNS cache container running but file ${ADAPT_DNS_IP_FILE} does not exist. >&2
exit 1
fi
fi
# We only support attaching to the default (host) bridge named "bridge".
DOCKER_HOST_NETWORK=bridge
# Confirm that "bridge" is the default bridge
IS_DEFAULT=$(docker network inspect "${DOCKER_HOST_NETWORK}" --format '{{(index .Options "com.docker.network.bridge.default_bridge")}}')
if [ "${IS_DEFAULT}" != "true" ]; then
echo Cannot start DNS cache. The Docker network named \"${DOCKER_HOST_NETWORK}\" does not exist or is not the default bridge. >&2
exit 1
fi
# Get the Linux interface name for the bridge, typically "docker0"
INTF_NAME=$(docker network inspect "${DOCKER_HOST_NETWORK}" --format '{{(index .Options "com.docker.network.bridge.name")}}')
if [ -z "${INTF_NAME}" ]; then
echo Cannot start DNS cache. Unable to determine default bridge interface name. >&2
exit 1
fi
# Get the IP address of the bridge interface. This is the address that
# dnsmasq will listen on and other containers will send DNS requests to.
IP_ADDR=$(interfaceIP "${INTF_NAME}")
if [ -z "${IP_ADDR}" ]; then
echo Cannot start DNS cache. Docker bridge interface ${INTF_NAME} does not exist. >&2
exit 1
fi
# Run the dnsmasq container. The hosts's /etc/resolv.conf configuration will
# be used by dnsmasq to resolve requests.
docker run --rm -d --cap-add=NET_ADMIN --name "${NAME}" --net=host -v/etc/resolv.conf:/etc/resolv.conf "${IMAGE}" --bind-interfaces --listen-address="${IP_ADDR}" --log-facility=- > /dev/null
if [ $? -ne 0 ]; then
echo Cannot start DNS cache. Docker run failed.
exit 1
fi
# Remember what IP address to use as DNS server, then output it.
echo ${IP_ADDR} > "${ADAPT_DNS_IP_FILE}"
echo ${IP_ADDR}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment