【问题标题】:Networking in Docker Compose fileDocker Compose 文件中的网络
【发布时间】:2020-03-19 10:48:34
【问题描述】:

我正在为我的网络应用程序编写一个 docker compose 文件。如果我使用“链接”将服务相互连接,是否还需要包含“端口”? “取决于”是“链接”的替代选项吗?什么最适合在撰写文件中相互连接服务?

【问题讨论】:

  • 'links' 是 docker compose 的遗留功能,即将消失。建议使用“用户自定义网络”。更多here

标签: docker networking service docker-compose hyperlink


【解决方案1】:

Networking in Compose 中描述了此的核心设置。如果您完全什么都不做,那么一个服务可以使用其在docker-compose.yml 文件中的名称作为主机名调用另一个服务,使用容器内的进程正在侦听的端口。

关于启动顺序问题,这里有一个最小的docker-compose.yml 来证明这一点:

version: '3'
services:
  server:
    image: nginx
  client:
    image: busybox
    command: wget -O- http://server/
    # Hack to make the example actually work:
    # command: sh -c 'sleep 1; wget -O- http://server/'

您根本不应该使用links:。它是第一代 Docker 网络的重要组成部分,但在现代 Docker 上没有用处。 (同样,没有理由将expose: 放在 Docker Compose 文件中。)

您始终连接到容器内的进程正在运行的端口。 ports: 是可选的;如果你有ports:,跨容器调用总是连接到 second 端口号并且重新映射没有任何效果。在上面的示例中,client 容器始终连接到默认的 HTTP 端口 80,即使您将 ports: ['12345:80'] 添加到 server 容器以使其在不同的端口上被外部访问。

depends_on: 影响两件事。尝试将depends_on: [server] 添加到示例的client 容器中。如果您查看 Compose 在启动时打印出的“正在启动...”消息,这将强制 serverclient 启动之前启动,但这不是保证server 已启动并运行并准备好服务请求(这是数据库容器的一个非常常见的问题)。如果您仅以docker-compose up client 开始堆栈的一部分,这也会导致server 以它开始。

更完整的典型示例可能如下所示:

version: '3'
services:
  server:
    # The Dockerfile COPYs static content into the image
    build: ./server-based-on-nginx
    ports:
      - '12345:80'
  client:
    # The Dockerfile installs
    # https://github.com/vishnubob/wait-for-it
    build: ./client-based-on-busybox
    # ENTRYPOINT and CMD will usually be in the Dockerfile
    entrypoint: wait-for-it.sh server:80 --
    command: wget -O- http://server/
    depends_on:
      - server

这个领域的 SO 问题似乎还有许多其他不必要的选项。 container_name: 为非 Compose docker 命令明确设置容器的名称,而不是让 Compose 选择它,它为网络目的提供了一个备用名称,但您并不真正需要它。 hostname: 影响容器的内部主机名(例如,您可能会在 shell 提示符中看到),但它对其他容器没有影响。您可以手动创建networks:,但Compose 为您提供了default 网络,没有理由不使用它。

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多