0%

Use dnsmasq Instead of /etc/hosts Inside Docker

Docker does not allow you to freely modify /etc/hosts inside a container. Attempts to do so usually end with permission errors, which has caused a lot of discussion over time.

Until Docker offers a cleaner built-in solution, one practical workaround is to use dnsmasq for local name resolution instead.

The example below assumes a CentOS 6 container.

1. Install dnsmasq

1
yum install dnsmasq

If you want dnsmasq to start automatically whenever the container starts, you can append the startup command to /.bashrc:

1
echo "service dnsmasq start &>/dev/null" >> /.bashrc

2. Configure dnsmasq

Edit /etc/dnsmasq.conf and add:

1
2
listen-address=127.0.0.1
addn-hosts=/etc/dnsmasq.hosts

This tells dnsmasq to listen on localhost and use /etc/dnsmasq.hosts as an additional hosts file.

3. Add custom host entries

Create or edit /etc/dnsmasq.hosts and add the hostnames you want to resolve. The format is the same as a normal hosts file.

4. Exit the container and save its changes

5. Start the container with custom DNS

When starting the container, add --dns so the container uses the local dnsmasq, plus a second DNS server for everything else:

1
docker run -t -i --dns=127.0.0.1 --dns=114.114.114.114 knktc/centos6 /bin/bash

At that point the container can resolve your custom local names just like it would with /etc/hosts.

Known issue

dnsmasq takes a little time to start. If you run a command immediately when the container starts, some lookups may fail early.

A simple workaround is to add a short delay:

1
docker run -t -i --dns=127.0.0.1 --dns=114.114.114.114 knktc/centos6 /bin/bash -ic "sleep 5;python myapp.py"
如果我的文字帮到了您,那么可不可以请我喝罐可乐?