同一节点中的复制服务 - Docker

Replicated service in the same node - Docker

我想要复制一个服务。

此服务在 Worker 角色上复制,在某些情况下,服务在同一节点中复制两次,而不是每个节点复制一次。

我有 docker-compose.yml

version: "3"
services:
  api-test:
    # replace username/repo:tag with your name and image details
    image: some-image
    deploy:
      replicas: 2
      placement:
        constraints:
          - node.role == worker
      restart_policy:
        condition: on-failure
    ports:
      - "4001:80"
    networks:
      - some-network
networks:
  some-network:

这实际上是 Docker Swarm 的正常行为。您会看到 Swarm 根据许多标准(每个工作人员的负载、可用性等)选择节点来部署服务

因此,如果您想确保在具有特定 label/role(例如 worker)的每个节点上复制服务,您应该使用 global 模式而不是 replicas (see here).

这样您的撰写文件将如下所示:

version: "3"
services:
  api-test:
    # replace username/repo:tag with your name and image details
    image: some-image
    deploy:
      mode: global
      placement:
        constraints:
          - node.role == worker
      restart_policy:
        condition: on-failure
    ports:
      - "4001:80"
    networks:
      - some-network
networks:
  some-network:

这将在每个 worker 节点上恰好部署一次您的 api-test 服务。

使用 1.13 中引入的 HA 调度策略 (see this PR),除非其他节点不可用于调度,否则 swarm 模式调度程序不应出现此行为。如果您定义了排除某个节点的约束,或者您定义了该节点上不可用的资源预留(CPU 和内存),则该节点可能无法用于调度。我在您提供的撰写文件中没有看到任何一个。

一个潜在的问题是重启策略。这定义了单个容器的重启策略,同时您还可以在中断后使用集群模式重新部署容器。结果可能是 运行 个副本过多。因此,我建议从您的服务中删除 restart_policy 部分,让 swarm 模式单独处理调度。

否则,我所见的一个节点上存在多个容器的主要原因是重启集群中的节点。 Swarm 模式将在静止 运行 个节点(或第一个重启的节点)上重新安排服务,并且一旦其他节点重新连接,它不会抢先停止 运行 任务以将其安排在另一个节点上。您可以使用以下命令强制服务重新平衡:

docker service update --force $service_name