Search code examples
linuxdockerdhcpdnsmasq

Run dnsmasq as DHCP server from inside a Docker container


I'm trying to get dnsmasq to operate as a DHCP server inside a Docker container, issuing DHCP addresses to machines on the host's physical network. I'm using the Alpine Linux 6MB container from https://hub.docker.com/r/andyshinn/dnsmasq/.

It works fine as a DNS server on port 53 on the host machine, however there is nothing listening on port 67/udp, which is where I'm expecting DHCP to be. I use dhcping 192.168.2.2, but get "no answer". telnet 192.168.2.2 67 returns "Connection refused".

My dnsmasq.conf file in the container looks like this:

interface=eth0
user=root
domain-needed
bogus-priv
no-resolv
local=/mydomain.io/
no-poll
server=8.8.8.8
server=8.8.4.4
no-hosts
addn-hosts=/etc/dnsmasq_static_hosts.conf
expand-hosts
domain=mydomain.io
dhcp-range=192.168.2.10,192.168.2.250,255.255.255.0,192.168.2.255,5m
# Have windows machine release on shutdown
dhcp-option=vendor:MSFT,2,1i
# No default route
dhcp-option=3

The host machine has a static address of 192.168.2.2.

I start the container like this:

docker run -d --name dns -p 192.168.2.2:67:67/udp -p 192.168.2.2:53:53/udp sitapati/dns

There is no firewall on this machine, which is running Ubuntu 16.04.

Things I've thought of/tried:

  • is it because eth0 in the container has an address on a completely different subnet? (docker inspect tells me it's 172.17.0.2 on the bridged interface)
  • does it need to use --net host? I tried that, and it still didn't work.

Solution

  • Yes, the container will have its own interfaces on a virtual subnet (the docker0 bridge network). So it will be trying to offer addresses on that subnet.

    Using --net host worked for me, I got the DHCP server working using something like the following command:

    docker run --name dnsmasq2 -t -v /vagrant/dnsmasq.conf:/opt/dnsmasq.conf -p 67:67/udp --net host centos
    

    --net host ensures that the container appears to using the host's networking stack rather than its own.

    dnsmasq -q -d --conf-file=/opt/dnsmasq.conf --dhcp-broadcast
    

    I also needed to add the --dhcp-broadcast flag to dnsmasq within the container to get it to actually broadcast DHCPOFFER messages on the network. For some reason, dnsmasq was trying to unicast the DHCPOFFER messages, and it was using ARP to try to get an address that had not yet been assigned.