自定义名称解析在Docker容器上失败

时间:2020-08-24 20:07:08

标签: docker ubuntu dns

我想为新容器自定义DNS配置。我正在使用--hostname标志设置 新容器的主机名。以下是用于测试主机名的docker命令:

docker run --rm --hostname rando alpine:latest nslookup rando

输出如下:

Server:     xxx.xxx.xxx.2
Address:    xxx.xxx.xxx.2:53

** server can't find rando.localdomain: NXDOMAIN

** server can't find rando.localdomain: NXDOMAIN

我正在使用ubuntu 19.10版本。以下是/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 directly to
# all known uplink DNS servers. This file lists all configured search domains.
#
# 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 xxx.xxx.xx.2
search localdomain

对于解决此问题的任何帮助,我将不胜感激。

关于, 兰多。

PS

我尝试显式创建桥接网络,但仍然无法正常工作。下面是执行的结果:

enter image description here

以下是容器中/etc/resolv.conf文件中的内容: enter image description here

以下是Docker版本: enter image description here

最新试验: enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试中有两个小错误:

--hostname选项不会创建DNS条目。它只是在容器中设置主机名。

此外,使用默认桥接网络的容器会从主机获取/etc/resolv.conf文件的副本(此NS对容器名称一无所知),而使用自定义网络的容器则使用Docker的嵌入式DNS服务器,它将外部DNS查找转发到主机上配置的DNS服务器。

您可以使用--name和/或--net-alias来创建DNS条目。

三个命令胜过1000个单词:

// Creating a custom docker bridge network
docker network create -d bridge so-demo

// Running the container in the network created above
docker run -it --network so-demo --name foo --net-alias bar --hostname foobar alpine:latest sh


// Check if the container name is resolved:
/ # nslookup foo
Server:     127.0.0.11
Address:    127.0.0.11:53
Non-authoritative answer:
Non-authoritative answer:
Name:   foo
Address: 172.22.0.2


// Check if the net-alias is resolved
/ # nslookup bar
Server:     127.0.0.11
Address:    127.0.0.11:53
Non-authoritative answer:
Non-authoritative answer:
Name:   bar
Address: 172.22.0.2


// The hostname is not resolved
/ # nslookup foobar
Server:     127.0.0.11
Address:    127.0.0.11:53
** server can't find foobar: NXDOMAIN
** server can't find foobar: NXDOMAIN


// ...the hostname is just set internally in the container: 
/ # hostname -f
foobar
/ # cat /etc/resolv.conf 
nameserver 127.0.0.11