docker配置DNS详解
原创大约 2 分钟
docker配置DNS详解
背景
有的时候主机的DNS,docker的DNS不想设置一致,或是部分场景需要,或是业务需要,故此有此主题。
默认docker容器的DNS是主机的DNS,那么原本更改主机的DNS就好了,但是运维反馈,腾讯云ECS的DNS会变动(离塞谱),由于没有权限访问一些模块,也没办法排查,找到根因,故此就以docker配置DNS为例,临时解决一下。
环境说明
# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.3 LTS
Release: 22.04
Codename: jammy
# docker info
Client: Docker Engine - Community
Version: 24.0.7
Context: default
Debug Mode: false
# 作为容器DNS测试
docker pull ubuntu:20.04
宿主机 Ubuntu 22.04.3 LTS
DNS查看
这台主机用的是内网的DNS
# resolvectl status | grep DNS
Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current Scopes: DNS
Protocols: +DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 192.168.xx.1
DNS Servers: 192.168.xx.1
Protocols: -DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
扩展内容,如果你需要更改主机的DNS,可以本站搜索
ubuntu22.04更改DNS
找找,应该有一些教程。
启动容器,验证DNS是宿主机的DNS
docker run -itd --name test ubuntu:20.04
docker exec -it test bash
root@76347263090f:/# cat /etc/resolv.conf
# This is /run/systemd/resolve/resolv.conf managed by man:systemd-resolved(8).
# Do not edit.
#
# This file might be symlinked as /etc/resolv.conf. If you're looking at
# /etc/resolv.conf and seeing this text, you have followed the symlink.
#
# This is a dynamic resolv.conf file for connecting local clients directly to
# all known uplink DNS servers. This file lists all configured search domains.
#
# Third party programs should typically 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 192.168.xx.1
search .
# 可以看到DNS是宿主机的DNS
修改 Docker 守护进程配置
/etc/docker/daemon.json
中 添加 DNS 配置:
{
"dns": ["8.8.8.8", "8.8.4.4"]
}
需要重启 docker ,
systemctl restart docker
root@76347263090f:/# cat /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
对单个容器修改DNS
需要重建容器
docker run -itd --name test --dns 8.8.4.4 --dns 114.114.114.114 ubuntu:20.04
docker exec -it test bash
root@b0548e7b21ca:/# cat /etc/resolv.conf
nameserver 8.8.4.4
nameserver 114.114.114.114