docker swarm:如何仅在运行任务的特定节点上发布服务

时间:2018-01-26 21:25:00

标签: docker port docker-swarm

我创建了一个docker-compose.yml文件,其中包含两个在两个不同节点上运行的服务。这两个服务旨在与客户端和服务器在同一端口上进行通信。下面是我的docker-compose.yml文件。

 version: "3"
services:
  service1:
    image: localrepo/image1
    deploy:
      placement:
        constraints: [node.hostname == node1]
      replicas: 1
      resources:
        limits:
          cpus: "1"
          memory: 1000M
      restart_policy:
        condition: on-failure
    ports:
      - 8000:8000
    networks:
      - webnet

  service2:
    image: localrepo/image2
    deploy:
      placement:
        constraints: [node.hostname == node2]
      replicas: 1
      resources:
        limits:
          cpus: "1"
          memory: 500M
      restart_policy:
        condition: on-failure
    ports:
      - "8000:8000"
    networks:
      - webnet
networks:
  webnet:

当我发出docker stack deploy -c时,我收到错误,请阅读

> Error response from daemon: rpc error: code = 3 desc = port '8000' is already in use by service.

在此thread中,我读到在swarm中部署服务使得端口可以在swarm中的任何节点上访问。如果我理解正确,那将使端口被集群中的任何节点占用。在同一个线程中,建议使用mode=host发布,这只会暴露容器运行的实际主机上的端口。我在端口中将其应用于:

端口:    - " mode = host,target = 8000,published = 8000"

在服务中进行更改并尝试发出docker stack会产生另一个错误:

> 1 error(s) decoding:

* Invalid containerPort: mode=host, target=8000, published=8000

有谁知道如何解决这个问题?

p.s:我试过了" Version3"和"版本3.2"但这个问题并没有解决。

2 个答案:

答案 0 :(得分:1)

升级到最新的泊坞窗版本18.01.0-ce

后,问题得以解决

答案 1 :(得分:0)

我不知道你是如何指定host mode的,因为你的docker-compose.yml并不代表host mode

顺便说一下,试试long syntax可以在host mode文件中指定docker-compose.yml

这个长语法是v3.2中的新语法,下面是示例(我检查它是否有效)

Thisdocker engine语法版本兼容docker-compose版本。)

version: '3.4'     # version: '3.2' also will works

networks:
    swarm_network:
        driver: overlay


services:
    service1:
        image: asleea/test

        command: ["nc", "-vlkp", "8000"]

        deploy:
            mode: replicated
            replicas: 1
            placement:
                constraints:
                    - node.hostname == node1

        ports:
            - published: 8000
              target: 8000
              mode: host

        networks:
            swarm_network:

    service2:
        image: asleea/test

        command: ["nc", "service1", "8000"]

        deploy:
            mode: replicated
            replicas: 1
            placement:
                constraints:
                    - node.hostname == node2

        ports:
            - published: 8000
              target: 8000
              mode: host

        networks:
            swarm_network: