DNS not working within docker containers when host uses dnsmasq and Google's DNS server are firewalled?

后端 未结 6 1405
难免孤独
难免孤独 2020-12-24 03:09

The symptom is: the host machine has proper network access, but programs running within containers can\'t resolve DNS names (which may appear to be \"can\'t access the netwo

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 04:06

    Since the automatic DNS discovery is guilty here, you may override the default setting in docker's configuration.

    First, get the IP of the DNS server dnsmasq is using with e.g.:

    $ sudo kill -USR1 `pidof dnsmasq`
    $ sudo tail /var/log/syslog 
    [...]
    Apr 24 13:20:19 host dnsmasq[2537]: server xx.yy.zz.tt1#53: queries sent 0, retried or failed 0
    Apr 24 13:20:19 host dnsmasq[2537]: server xx.yy.zz.tt2#53: queries sent 0, retried or failed 0
    

    The IP addresses correspond to the xx.yy.zz.tt placeholders above.

    You can set the DNS at docker run time with the --dns option:

    $ sudo docker run --dns xx.yy.zz.tt1 --dns xx.yy.zz.tt2 -ti mmoy/ubuntu-netutils bash
    root@6c5d08df5dfd:/# ping www.example.com
    PING www.example.com (93.184.216.34) 56(84) bytes of data.
    64 bytes from 93.184.216.34: icmp_seq=1 ttl=54 time=86.6 ms
    64 bytes from 93.184.216.34: icmp_seq=2 ttl=54 time=86.6 ms
    

    One advantage of this solution is that there is no configuration file involved, hence no risk of forgetting about the configuration and running into troubles later because of a specific config: you're getting this DNS configuration if and only if you type the --dns option.

    Alternatively you may set it permanently in Docker's configuration file, /etc/docker/daemon.json (create it, on the host, if it doesn't exist):

    $ cat /etc/docker/daemon.json
    {
        "dns": ["xx.yy.zz.tt1", "xx.yy.zz.tt2"]
    }
    

    You need to restart the docker daemon to take the daemon.json file into account:

    sudo service docker restart
    

    Then you can check the configuration:

    $ sudo docker run -ti mmoy/ubuntu-netutils bash
    root@56c74d3bd94b:/# cat /etc/resolv.conf 
    nameserver xx.yy.zz.tt1
    nameserver xx.yy.zz.tt2
    root@56c74d3bd94b:/# ping www.example.com
    PING www.example.com (93.184.216.34) 56(84) bytes of data.
    64 bytes from 93.184.216.34: icmp_seq=1 ttl=54 time=86.5 ms
    

    Note that this hardcodes the DNS IP in your configuration files. This is strongly discouraged if your machine is a laptop that connects to different networks, and may be problematic if your internet service provider changes the IP of the DNS servers.

提交回复
热议问题