在特定端口和主机名中部署副本

dve*_*ti3 4 docker docker-compose docker-swarm

我需要在集群中部署一个 docker 容器。我想部署 4 个 docker 容器的副本。我想设置每个容器将运行的端口,并且我需要知道它们的主机名。

我想要的是吃 4 个复制品的午餐。

  • 副本 1 应侦听端口 3001 和主机名 Slave1。
  • 副本 2 应侦听端口 3002 和主机名 Slave2。
  • 副本 3 应侦听端口 3003 和主机名 Slave3。
  • 副本 4 应侦听端口 3004 和主机名 Slave4。

每个副本都有相同的 Dockerfile(因为我要运行的进程是相同的)。在 Dockerfile 中,我使用标准命令公开所有 4 个端口: EXPOSE 3001 3002 3003 3004

我尝试了这个 docker-compose 文件,其中使用 4 个端口并使用“mode:replicated”进行部署

services:
  slave:
    image: "DOCKER_REPO_NAME"
    deploy:
      mode: replicated
      replicas: 4
      restart_policy: 
        condition: on-failure
    networks:
      - my_net
    ports:
      - "3001:3001"
      - "3002:3002"
      - "3003:3003"
      - "3004:3004"

networks:
  my_net:
    external: true 
Run Code Online (Sandbox Code Playgroud)

但它并没有像我想的那样工作,如上所述。

希望问题的描述有意义。请告诉我。

cod*_*aus 7

我认为您分别误解了 docker swarm 模式的工作方式。Swarm 模式不适用于容器/节点级别,但它是更高的抽象级别 - 它与服务一起使用。

服务由在给定数量的节点上运行的给定数量的容器实例组成。Swarm 将处理 Swarm 中运行的容器实例数量,并将处理服务容器在哪些节点上运行(当然,您可以使用 和 等参数进行配置replicasconstraints

Swarm 模式的一大好处是您不需要了解有关 Swarm 基础设施的任何信息。您不关心那里有哪些节点以及哪个容器正在哪个节点上运行。

相反,您只需告诉 Swarm 您想要联系什么服务,Swarm 模式将决定将您的请求分派到哪个节点上的哪个容器。

因此,在您的示例中,如果您的服务在端口 3001 上运行,并且假设有一个名为的 api 端点,GET /hello您将请求http://slave:3001/hello。这就是集群模式发挥作用的地方,因为它知道哪些容器在哪些节点上运行,所以它将决定将您的请求转发到哪里。

如果您想让特定容器侦听特定节点上的特定端口,您必须定义多个服务并使用约束和标签配置这些服务。因此您的 docker-compose.yml 看起来像这样:

services:
  slave1:
    image: "DOCKER_REPO_NAME"
    deploy:
      mode: replicated
      replicas: 1
      placement:
        constraints:
          - node.labels.type == slave1
      restart_policy: 
        condition: on-failure
    networks:
      - my_net
    ports:
      - "3001:3001"
  slave2:
    image: "DOCKER_REPO_NAME"
    deploy:
      mode: replicated
      replicas: 1
      placement:
        constraints:
          - node.labels.type == slave2
      restart_policy: 
        condition: on-failure
    networks:
      - my_net
    ports:
      - "3002:3001"
  slave3:
    image: "DOCKER_REPO_NAME"
    deploy:
      mode: replicated
      replicas: 1
      placement:
        constraints:
          - node.labels.type == slave3
      restart_policy: 
        condition: on-failure
    networks:
      - my_net
    ports:
      - "3003:3001"
  slave4:
    image: "DOCKER_REPO_NAME"
    deploy:
      mode: replicated
      replicas: 1
      placement:
        constraints:
          - node.labels.type == slave4
      restart_policy: 
        condition: on-failure
    networks:
      - my_net
    ports:
      - "3004:3001"

networks:
  my_net:
    external: true 
Run Code Online (Sandbox Code Playgroud)

但请注意,这会破坏 swarm 的大部分优势。