【问题标题】:Get exposed port from within docker-compose从 docker-compose 中获取公开的端口
【发布时间】:2021-01-26 05:08:46
【问题描述】:

我有一个 docker-compose.yml 文件如下:

version: "3.9"
services:
  server:
    build: .
    ports:
      - "8086"
    environment:
      - PORT=8086

一个码头文件:

FROM python:3.8

RUN python -m pip install --upgrade pip
RUN pip install pipenv

COPY Pipfile* /app/

RUN cd /app &&  pipenv lock --keep-outdated --requirements > requirements.txt

RUN pip install -r /app/requirements.txt

COPY . /app/src

WORKDIR /app/src

EXPOSE ${PORT}

CMD uwsgi --http :${PORT} --wsgi-file server.py --callable main

所以基本上,我在给定端口上运行服务器,我在 Dockerfile 和 docker-compose 中公开了该端口。但是,当我运行这些容器的两个实例时,我需要一种方法让它们各自使用自己的端口。我也不能硬编码值,因为我需要能够扩展到 n 个实例。因此,我需要以某种方式从正在运行的容器中获取每个端口,将其公开,然后在该端口上运行服务器,而不是使用环境变量 PORT

当我调用docker-compose up --scale server=2 来运行两个服务器容器时,我无法发送 HTTP 请求,因为端口映射不匹配。

基本上我要做的是让每个容器使用 docker-compose 分配给它的端口运行 uwsgi。有什么方法可以很好地实现这一点吗?

示例:

来源:https://github.com/distribworks/dkron

【问题讨论】:

    标签: python docker docker-compose uwsgi


    【解决方案1】:

    您的server 服务定义中缺少HOST_PORT 部分。根据https://docs.docker.com/compose/networking/,服务的端口定义应为HOST_PORT:CONTAINER_PORT。否则会随机选择一个HOST_PORT

    您可以克隆一个工作示例环境here 或查看它是否工作here

    您始终可以通过发出以下命令查看 Docker Compose 选择的端口:

    jdsalaro$ docker ps
    
    CONTAINER ID   IMAGE                                                         COMMAND                  CREATED          STATUS          PORTS                     NAMES
    de0120c61c1e   65896179-get-exposed-port-from-within-docker-compose_server   "/bin/sh -c 'uwsgi -…"   12 seconds ago   Up 11 seconds   0.0.0.0:49157->8086/tcp   65896179-get-exposed-port-from-within-docker-compose_server_1
    

    要解决您的问题,只需提供HOST_PORT 即可:

    version: "3.9"
    services:
      server:
        build: .
        ports:
          - "8086:8086"
        environment:
          - PORT=8086
    

    当使用--scale,例如--scale server=4,可以提供一系列端口为HOST_PORT,而不是如下:

    version: "3.9"
    services:
      server:
        build: .
        ports:
          - "8000-8004:8086"
        environment:
          - PORT=8086
    

    【讨论】:

    • (这两个端口号不需要匹配,可以选择一个固定的容器端端口号并通过ports:重新映射。这样会简化你的镜像设置。)跨度>
    • 嗯,当我尝试这个时,我得到错误:Bind for 0.0.0.0:8086 failed: port is already allocated 当我运行 docker-compose up --scale server=2
    • ^ 我相信这是我的根本问题:我需要能够使用docker-compose up --scale server=n 运行两个(或更多)服务器,而它们的端口不会发生冲突。我知道这可以(以某种方式)完成,因为我已经看到了一个示例实现(但使用 go 而不是 python/uwsgi——我在上面添加了图片)
    • 关于Bind for 0.0.0.0:8086 failed: port is already allocated 错误,这是预期的,因为--scale server=2 中的第一个实例已经分配了端口8086,并且没有为第二个实例留下端口8086。跨度>
    • 至于I need to be able to run two (or more) servers,这也是可能的,我应该在我的答案中添加这部分。当使用--scale 时,您可以在服务定义中使用一系列端口作为HOST_PORT,例如8000-8004:8086。我已经更新了我的答案和the example project accordingly
    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多