首页 > 解决方案 > 如何确保每个 docker swarm 节点只有一个服务实例

问题描述

我想部署一个从多台现场机器收集传感器数据的 docker swarm。

是否可以确保在 docker swarm 中的每个工作节点上都启动特定服务的一个容器?

我正在寻找比将服务扩展到与 docker 节点数量相同数量的副本更可预测的东西。

同时注意;我想避免将服务部署到任何管理器节点。这可能吗?

标签: docker

解决方案


实现此目的的一种方法是使用全局模式进行部署,使用主机模式公开端口。在全局模式下,部署的服务基于放置约束。因此,如果您想在 2 个工作节点上运行 Nginx 服务,您可以使用以下 docker-compose 文件来实现。

version: '3.2'

networks:
  testnetwork:
    driver: overlay
    attachable: true

services:
  nginx1:
    image: nginx:latest
    ports:
      - target: 80
        published: 80
        protocol: tcp
        mode: host
    networks:
      testnetwork:
        aliases:
          - nginx1.test.com
    deploy:
      mode: global
      restart_policy:
        condition: on-failure
        max_attempts: 3
      placement:
        constraints: [node.hostname == worker1]
version: '3.2'

networks:
  testnetwork:
    driver: overlay
    attachable: true

services:
  nginx2:
    image: nginx:latest
    ports:
      - target: 80
        published: 80
        protocol: tcp
        mode: host
    networks:
      testnetwork:
        aliases:
          - nginx2.test.com
    deploy:
      mode: global
      restart_policy:
        condition: on-failure
        max_attempts: 3
      placement:
        constraints: [node.hostname == worker2]

您可以看到placement.constraints定义了应该部署服务的节点的主机名,您也可以使用IP。

暴露的端口特定于部署节点的主机,不会与其他主机的端口冲突。如果服务需要公开多个端口,您可以在“端口”部分添加更多端口。确保服务名称和别名不会相互冲突。


推荐阅读