docker 容器上的自定义名称解析失败

问题描述 投票:0回答:2

我想为新容器自定义 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

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

问候, 兰多。

P.S

我尝试显式创建桥接网络,但仍然不起作用。下面是执行结果:

enter image description here

以下是容器内

/etc/resolv.conf
文件的内容: enter image description here

以下是docker版本: enter image description here

最新试验: enter image description here

enter image description here

docker ubuntu dns
2个回答
1
投票

您的尝试中有两个小错误:

--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



0
投票

对于从《Docker in action 第一版》一书中读到这里的人来说,该示例显示了以下过时的命令。

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

自第一版编写以来发生了很多变化。 《Docker 实战第二版》阐述了卷和网络的新概念。所以我建议你去读那本书而不是第一篇。至于这个问题,Neo 回答得很好。但对于任何从第一版开始寻找答案的人来说,都应该遵循以下步骤。

通过运行创建docker网络

docker network create development

然后使用以下命令运行容器

docker run --rm --network development --net-alias barker alpine:latest nslookup barker
© www.soinside.com 2019 - 2024. All rights reserved.