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

custom name resolution failing on docker container

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

我试图显式创建桥接网络,但仍然没有成功。下面是执行结果:

以下是容器内 /etc/resolv.conf 文件的内容:

以下是 docker 版本:

最新试验:

您的尝试有两个小错误:

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

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

您可以使用 --name and/or --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