1. 程式人生 > >完美解決K8s中的Pod無法解析外網域名問題

完美解決K8s中的Pod無法解析外網域名問題

127.0.0.1 coredns rep 保留 內容 support 拷貝 -- dns

系統:Ubuntu 18.04.02
K8s版本:1.13.4

故障現象:Pod內無法ping通外網域名,訪問外網IP、K8s內部域名或者IP均正常

原因分析:K8s在創建Pod時會把宿主機的/etc/resolv.conf裏的內容拷貝到Pod同文件中,如果/etc/resolv.conf裏寫的配置不正確,則Pod無法解析外網域名。
Ubuntu18.04已經拋棄/etc/resolv.conf用做域名解析,DNS可以配置在/etc/netplan/xx.yaml中,保留/etc/resolv.conf只是用做兼容,查看該文件cat /etc/resolv.conf:

# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "systemd-resolve --status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0

根據註釋,我們知道,/etc/resolv.conf由systemd-resolved服務管理,不建議手工修改,因為會被自動覆蓋,同時ls該文件,發現/etc/resolv.conf只不過是一個軟鏈接

網上方法:修改/etc/systemd/resolved.conf中的DNS項,之後重啟systemd-resolved服務,經驗證無效。

最終解決辦法:刪除該軟鏈接,然後自己手工創建該文件

rm /etc/resolv.conf -f
cat /etc/resolv.conf<<EOF
nameserver 114.114.114.114
nameserver 114.114.115.115
EOF

帶來的問題:unable to resolve host xxx,解決辦法:編輯/etc/hosts,把你的主機名加到127.0.0.1行即可

刪除Pod之後重新創建Pod,問題完美解決

註意:KubeDNS或者CoreDNS在修改/etc/resolv.conf前已經創建,也必須刪除之後重建

完美解決K8s中的Pod無法解析外網域名問題