gpt4 book ai didi

通过主机名发现 Docker 容器不起作用

转载 作者:行者123 更新时间:2023-12-02 19:21:53 24 4
gpt4 key购买 nike

我使用位于 /tmp/compose.yml 的以下 docker compose 文件进行 docker 堆栈部署:

version: "3.6"

services:
service-A:
image: service-A
networks:
- net
hostname: "service-A-{{.Task.Slot}}"
deploy:
replicas: 2

service-B:
image: service-B
networks:
- net
hostname: "service-B-{{.Task.Slot}}"
deploy:
replicas: 2

networks:

net:

运行命令:

docker network create -d overlay net
docker stack deploy -c /tmp/compose.yml my

我的期望是 service-A 单个容器将能够通过容器预定义的主机名发现 service-B 容器:service-B-1,服务-B-2。但是,从任何 service-A 容器中 ping service-B-1 都会失败。

Docs状态:

hostname Sets the hostname by which the container knows itself. This is written into /etc/hostname, into /etc/hosts as the name of the container's host-facing IP address, and is the name that /bin/bash inside the container will display inside its prompt. But the hostname is not easy to see from outside the container. It will not appear in docker ps nor in the /etc/hosts file of any other container.

如何通过容器预定义的主机名实现 docker swarm 服务容器到服务容器的通信?

唯一可行的方法是添加如下条目:

[service_B_container_1_virtual_ip] service-B-1
[service_B_container_2_virtual_ip] service-B-2

service-A 容器的 /etc/hosts

有趣的是,如果 hostname 没有在 docker-composes 文件中设置,而是由 docker 生成,ping [container_id] 甚至会成功跨多主机 docker 群。

我希望预定义的主机名有相同的行为。

最佳答案

我认为没有任何直接的方法可以做到这一点。我越想越觉得不应该有一种方法来完成你所要求的,设计

堆栈服务的一个基本属性是,它应该以 Docker 能够互换地处理该服务中的所有副本的方式进行部署。如果您需要连接到单个实例,它建议首先不应将这些容器创建为服务副本,因为有一些东西可以区分它们。适当的堆栈服务应该能够将每个副本视为可以随时销毁和重建的临时实体,并且操作应该从外部不可见。

您在 Docker 网络内部可以做的是使用服务名称引用服务实体。因此,在您的示例中,ping Service-A 应该适用于堆栈中的任何容器,ping Service-B 也是如此。

服务中各个容器的名称是这样的

my_stack_redis.1.y1pwzeg8239yb6n6ynefs78br
my_stack_webserver.1.d6cxx8nlg7db9m2poy9wfjdyd

如果您绝对必须从容器内访问这些名称,我能想到的唯一方法是在启动时通过绑定(bind)挂载在容器内公开 /var/run/docker.sock .然后,chmod 750 在套接字上作为 CMD/ENTRYPOINT 脚本的一部分,以便非根用户可以读取它。现在您应该能够安装 Docker CLI 并使用 docker network inspect 来发现实际服务成员的名称,并使用 jq 来解析它们(您可能需要将两个包都添加到图像中)。但在这一点上,更好的选择可能是将那些不可替代的容器分离到它们自己的服务组中。

关于通过主机名发现 Docker 容器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59055358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com