Docker dns not working

在容器里面无法通过域名访问网络,但可以使用ip ping通。这可能是 dns 解析出现了问题。

1
2
3
4
nslookup security.debian.org
nslookup: can't resolve '(null)': Name does not resolve

nslookup: can't resolve 'security.debian.org': Try again

dns解析出现问题时可能与宿主机的 /etc/resolv.conf 文件相关。

关于container 的 /etc/resolv.conf 文件官方描述

docker dns 文档.png

container‘s /etc/resolv.conf 与 宿主机的 /etc/resolv.conf 相似,只是使用过滤器把 localhost 的地址进行过滤。

宿主主机是使用 ubuntu

ubuntu server

如果使用 ubuntu server 那么需要手动修改 /etc/network/interfaces

应该与下面相似

1
2
3
4
5
6
7
8
9
10
11
12
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto enp0s3
iface enp0s3 inet dhcp

重启网卡

1
2
3
ifdown enp0s3
ifup enp0s3
resolvconf -u # 更新 /etc/resolv.conf

/etc/resolv.conf 与下面类似

1
2
3
4
5
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 202.192.18.10
nameserver 202.192.18.1
nameserver 202.192.18.2

ubuntu 桌面版

因为ubuntu 桌面版是使用 network-manager 进行自动管理

检查 /etc/network/interfaces 应该与下面相似,不需要手动管理其他网卡

1
2
auto lo
iface lo inet loopback

更新 /etc/resolv.conf

1
2
service network-manager restart
resolvconf -u

这时候 /etc/resolv.conf 应该恢复正常,重新创建容器应该可以正常解析域名了。