全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-21 6 分钟 ✍️ juanwangdev

多容器编排启动

Docker Compose 可一键启动多容器应用,下面介绍编排方法与注意事项。

快速启动

Bash
# 启动所有服务(后台运行)
docker compose up -d

# 前台运行(查看日志)
docker compose up

# 重建并启动
docker compose up -d --build

# 强制重建
docker compose up -d --build --force-recreate

服务启动顺序

depends_on 基础

YAML
version: '3.8'

services:
  web:
    image: nginx
    depends_on:
      - app
  
  app:
    build: .
    depends_on:
      - db
      - redis
  
  db:
    image: postgres:15
  
  redis:
    image: redis:7

启动顺序:db/redis → app → web。但 depends_on 不等待服务就绪,仅等待容器启动。

depends_on 条件检查

YAML
version: '2.1'  # 需要 2.1+ 版本

services:
  web:
    image: nginx
    depends_on:
      app:
        condition: service_healthy
  
  app:
    build: .
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:15
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5

使用 condition: service_healthy 等待健康检查通过,但需要配置 healthcheck。

扩缩容

YAML
# docker-compose.yml
services:
  worker:
    build: ./worker
    deploy:
      replicas: 3
Bash
# 启动时指定副本数
docker compose up -d --scale worker=5

# Compose V2
docker compose up -d --scale web=3

查看服务状态

Bash
# 查看所有服务状态
docker compose ps

# 查看日志
docker compose logs
docker compose logs -f app  # 实时查看

# 查看指定服务
docker compose ps app

# 查看端口映射
docker compose port web 80

停止与清理

Bash
# 停止所有服务
docker compose stop

# 停止并删除容器
docker compose down

# 停止并删除容器、网络、数据卷
docker compose down -v

# 删除构建缓存
docker compose down --rmi all

执行命令

Bash
# 在服务中执行命令
docker compose exec app /bin/bash
docker compose exec db psql -U postgres

# 一次性命令
docker compose run --rm app python manage.py migrate

环境变量管理

YAML
services:
  app:
    environment:
      - NODE_ENV=production
      - DB_HOST=db

# 或使用 env_file
services:
  app:
    env_file:
      - .env
      - .env.production

# 或使用 .env 文件(自动加载)

.env 文件:

Bash
DB_HOST=db
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=postgres123

多环境配置

YAML
# 使用不同 Compose 文件
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d

# 覆盖配置

docker-compose.yml(基础):

YAML
services:
  app:
    build: .
    environment:
      NODE_ENV: development

docker-compose.prod.yml(生产覆盖):

text
services:
  app:
    image: my-app:prod
    environment:
      NODE_ENV: production

要点总结

  • docker compose up -d 一键启动所有服务
  • depends_on 控制启动顺序,不保证服务就绪(需 healthcheck)
  • --scale 参数横向扩展服务副本
  • docker compose down -v 停止并删除数据卷,谨慎使用
  • 使用 .env 文件或 env_file 管理环境变量
  • 多环境使用多个 Compose 文件覆盖配置

📝 发现内容有误?点击此处直接编辑

← 上一篇 docker-compose.yml 语法
下一篇 → 扩缩容与负载均衡
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库