如何使尚未启动的容器的 DNS 条目在另一个容器中可用?

How do I make a DNS entry for a not yet started container available in another container?

我正在尝试 运行 一组容器。每个实例都通过环境变量获得其他实例的主机和端口列表。 我想使用 docker 网络(即,不是主机网络)。我的想法是通过“--name”(或--network-alias)运行选项给每个实例一个明确的主机名。

所以我想这样开始:

docker run --name x1 -e clusterMembers=x2:12345,x3:12345 --network=mynet -d my/image
docker run --name x2 -e clusterMembers=x1:12345,x3:12345 --network=mynet -d my/image
docker run --name x3 -e clusterMembers=x1:12345,x2:12345 --network=mynet -d my/image

问题是当我启动第一个引用主机名 x2 和 x3 的容器时,这些主机名通过 Docker 网络 DNS 尚不存在。我的服务器启动,进行查找,但失败,然后服务器再次退出(不,我无法更改代码以重试 DNS 查找)。 请注意,如果其他实例尚不可访问,服务器不会失败...只是它不能容忍失败的 DNS 查找。

知道如何使主机名 x2 和 x3 可用于容器 x1(以及主机名 x3 可用于容器 x2)吗?

我尝试了“--add-host”选项来向 /etc/hosts 文件中添加一个假条目,但是当然这个假条目将 "shadow" DNS 查找和服务器即使启动了其他实例,也永远不会看到正确的 IP 地址。

除了使用主机网络之外,还有什么方法可以做到这一点?


我根据 BMitch 的建议提出的解决方案是采用 wait-for-it 脚本,稍微调整一下,这样就可以代替 "pinging" 一个主机 + 端口,而只是执行一个给定主机的 DNS 查找。

然后,在我的容器入口点脚本中,我首先从上面示例中的 "clusterMembers" 环境变量中提取主机名,然后对每个主机名使用我的 wait-for-dns 脚本。

我会在图像中更改或添加一个入口点来执行类似 wait-for-it 的操作。然后您可以按任何顺序启动您的容器,而无需担心竞争条件或为尚不存在的容器注入 DNS 地址。

I tried the "--add-host" option to add a fake entry to the /etc/hosts file, but of course this fake entry will then "shadow" the DNS lookup, and the server will never see the right IP address even once the other instances are started.

我建议您将此方法与为每个容器分配特定 IP 地址相结合:

docker run --name x1 --add-host="x2:172.17.42.102" --add-host="x3:172.17.42.103" --ip="172.17.42.101" --network=mynet -d my/image