问题描述
我有数据库和服务器容器,它们都在同一网络中运行。可以通过其容器ID对数据库主机进行ping操作,没有问题。
当我手动设置数据库容器的主机名( -h myname
)时,它会起作用( $主机名
返回设置的主机),但是我无法从同一网络中的另一个容器ping该主机名。容器ID仍可ping通。
尽管它在docker compose中没有问题。
我缺少了什么?
I've had db and server container, both running in the same network. Can ping db host by its container id with no problem.When I set a hostname for db container manually (-h myname
), it had an effect ($ hostname
returns set host), but I can't ping that hostname from another container in the same network. Container id still pingable.Although it works with no problem in docker compose.What am I missing?
推荐答案
泊坞窗的内置DNS服务未使用主机名。这是一个违反直觉的例外,但是由于主机名可以在Docker的控制范围之外更改,所以这是有道理的。 Docker的DNS将解析:
Hostname is not used by docker's built in DNS service. It's a counterintuitive exception, but since hostnames can change outside of docker's control, it makes some sense. Docker's DNS will resolve:
- 容器ID
- 容器名称
- 您为该网络上的容器定义的任何网络别名
这些选项中最简单的是最后一个自动在运行带有撰写文件的容器时配置。服务名称本身是网络别名。这样一来,您就可以扩展和执行滚动更新,而无需重新配置其他容器。
The easiest of these options is the last one which is automatically configured when running containers with a compose file. The service name itself is a network alias. This lets you scale and perform rolling updates without reconfiguring other containers.
您需要使用用户创建的网络,而不是默认的已禁用DNS的网桥。在运行带有撰写文件的容器时,默认情况下会执行此操作。
You need to be on a user created network, not something like the default bridge which has DNS disabled. This is done by default when running containers with a compose file.
请避免使用链接,因为它们已被弃用。而且我只建议为不在任何DNS中的外部静态主机,容器到容器或访问docker以外的其他主机添加主机条目,首选DNS。
Avoid using links since they are deprecated. And I'd only recommend adding host entries for external static hosts that are not in any DNS, for container to container, or access to other hosts outside of docker, DNS is preferred.
这篇关于无法从同一网络中的另一个Docker容器解析集合主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!