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 在启动时打印出的“正在启动...”消息,这将强制 server 在 client 启动之前启动,但这不是保证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 网络,没有理由不使用它。