目录
Docker Compose YAML 用法指南
/    

Docker Compose YAML 用法指南

Docker Compose 语法指南

本文档基于 dify-main/docker/docker-compose.yaml 文件,整理了10个重要的Docker Compose语法知识点,并附有详细示例。

1. YAML锚点与引用 (YAML Anchors & References)

用途:定义可重用的YAML片段,避免重复配置。

语法

  • &name 定义锚点
  • *name 引用锚点
  • <<: *name 合并锚点内容

示例

# 定义共享环境变量锚点
x-shared-env: &shared-api-worker-env
  LOG_LEVEL: ${LOG_LEVEL:-INFO}
  DB_HOST: ${DB_HOST:-db}
  DB_PORT: ${DB_PORT:-5432}

# 在多个服务中复用
services:
  api:
    environment:
      <<: *shared-api-worker-env  # 合并所有共享变量
      MODE: api
    
  worker:
    environment:
      <<: *shared-api-worker-env  # 复用相同配置
      MODE: worker
# 定义基础服务配置锚点
x-base-service: &base-service
  restart: unless-stopped
  networks:
    - default
  logging:
    driver: "json-file"
    options:
      max-size: "10m"
      max-file: "3"

# 直接引用锚点(不使用合并)
services:
  nginx:
    <<: *base-service  # 合并基础配置
    image: nginx:alpine
    ports:
      - "80:80"
    
  redis:
    <<: *base-service  # 复用相同的基础配置
    image: redis:alpine
  
# 定义卷配置锚点
x-volumes: &app-volumes
  - ./app:/app
  - ./logs:/app/logs

# 引用卷锚点
services:
  web:
    volumes: *app-volumes  # 直接引用整个卷列表
  
  worker:
    volumes: *app-volumes  # 复用相同的卷配置

2. 环境变量默认值 (Environment Variables with Defaults)

用途:提供环境变量的默认值,增强配置的灵活性。

语法${VARIABLE:-default_value}

示例

services:
  db:
    environment:
      # 如果POSTGRES_USER未设置,使用默认值"postgres"
      POSTGRES_USER: ${POSTGRES_USER:-postgres}
    
      # 如果POSTGRES_PASSWORD未设置,使用默认值"difyai123456"
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-difyai123456}
    
      # 复杂默认值:嵌套变量引用
      POSTGRES_DB: ${POSTGRES_DB:-${DB_DATABASE:-dify}}

3. 服务依赖与健康检查 (Service Dependencies & Health Checks)

用途:确保服务按正确顺序启动,等待依赖服务就绪。

语法

  • depends_on 定义服务依赖
  • condition: service_healthy 等待服务健康检查通过

示例

services:
  api:
    depends_on:
      db:
        condition: service_healthy  # 等待db服务健康状态
      redis:
        condition: service_started  # 等待redis服务启动
  
  db:
    image: postgres:15-alpine
    healthcheck:
      test: ['CMD', 'pg_isready', '-h', 'db', '-U', 'postgres']
      interval: 1s
      timeout: 3s
      retries: 60

4. 卷挂载与命名卷 (Volume Mounts & Named Volumes)

用途:持久化数据,实现主机与容器之间的文件共享。

语法

  • ./host/path:/container/path 主机路径挂载
  • volume_name:/container/path 命名卷挂载

示例

services:
  api:
    volumes:
      # 主机路径挂载(相对路径)
      - ./volumes/app/storage:/app/api/storage
    
      # 命名卷挂载(由Docker管理)
      - app_data:/app/data
    
      # 只读挂载
      - ./config/nginx.conf:/etc/nginx/nginx.conf:ro

volumes:
  # 定义命名卷
  app_data:
    driver: local
  
  # 使用外部预创建卷
  external_data:
    external: true

5. 网络配置 (Network Configuration)

用途:定义容器间通信的网络,实现网络隔离。

语法

  • networks 定义网络
  • internal: true 创建内部网络(禁止外部访问)

示例

services:
  api:
    networks:
      - default          # 默认网络
      - ssrf_proxy_network  # 自定义网络

  sandbox:
    networks:
      - ssrf_proxy_network  # 加入同一网络实现通信

networks:
  # 内部网络(隔离外部访问)
  ssrf_proxy_network:
    driver: bridge
    internal: true
  
  # 外部可访问网络
  web_network:
    driver: bridge
    ipam:
      config:
        - subnet: 172.20.0.0/16

6. Profile配置 (Service Profiles)

用途:定义可选服务组,通过命令行参数控制启动。

语法profiles: ["profile_name"]

示例

services:
  # 默认启动的服务(无profile)
  api:
    image: dify-api:latest
  
  db:
    image: postgres:15-alpine
  
  # 可选服务:调试工具
  redis-commander:
    image: rediscommander/redis-commander:latest
    profiles: ["debug"]
    ports:
      - "8081:8081"
    
  # 可选服务:监控
  prometheus:
    image: prom/prometheus:latest
    profiles: ["monitoring"]
    ports:
      - "9090:9090"
    
  # 多个profile的服务
  grafana:
    image: grafana/grafana:latest
    profiles: ["monitoring", "debug"]
    ports:
      - "3000:3000"

使用方式

# 启动默认服务
docker-compose up

# 启动debug profile的服务
docker-compose --profile debug up

# 启动多个profile
docker-compose --profile debug --profile monitoring up

7. 条件重启策略 (Restart Policies)

用途:定义容器退出后的重启行为。

语法restart: [no|always|on-failure|unless-stopped]

示例

services:
  # 始终重启(除非手动停止)
  nginx:
    restart: unless-stopped
  
  # 只在失败时重启
  api:
    restart: on-failure
    restart_delay: 5s
  
  # 始终重启(无论退出状态)
  worker:
    restart: always
  
  # 不自动重启(默认)
  temp-job:
    restart: "no"

8. 多阶段构建与上下文 (Multi-stage Builds & Context)

用途:优化镜像构建过程,减少最终镜像大小。

语法target: build_stage_name

示例

services:
  # 使用Dockerfile的多阶段构建
  api:
    build:
      context: ./api
      dockerfile: Dockerfile
      target: production  # 只构建到production阶段
    
  # 开发环境使用不同阶段
  api-dev:
    build:
      context: ./api
      dockerfile: Dockerfile
      target: development  # 构建到development阶段
    volumes:
      - ./api:/app
  
  # 自定义构建参数
  nginx:
    build:
      context: ./nginx
      dockerfile: Dockerfile
      args:
        - NGINX_VERSION=1.25
        - BUILD_ENV=production

9. 命令与入口点 (Command & Entrypoint)

用途:覆盖容器的默认启动命令和入口点。

语法

  • command: 覆盖默认命令
  • entrypoint: 覆盖默认入口点

示例

services:
  # 覆盖默认命令
  redis:
    image: redis:alpine
    command: redis-server --appendonly yes --maxmemory 256mb
  
  # 自定义入口点
  nginx:
    image: nginx:alpine
    entrypoint: /docker-entrypoint.sh
    command: ["nginx", "-g", "daemon off;"]
  
  # 使用shell命令
  db-backup:
    image: postgres:15-alpine
    command: >
      sh -c "while true; do
        pg_dump -h db -U postgres dify > /backup/daily.sql
        sleep 86400
      done"
  
  # 多命令执行
  init-service:
    image: alpine:latest
    command: ["sh", "-c", "echo 'Starting...' && ./migrate.sh && ./start.sh"]

10. 资源限制 (Resource Limits)

用途:限制容器使用的系统资源,防止资源耗尽。

语法deploy.resources.limits

示例

services:
  # 内存和CPU限制
  api:
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
        reservations:
          cpus: '0.5'
          memory: 512M
  
  # 数据库资源限制
  db:
    deploy:
      resources:
        limits:
          cpus: '4.0'
          memory: 4G
        reservations:
          cpus: '1.0'
          memory: 1G
  
  # 轻量级服务
  redis:
    deploy:
      resources:
        limits:
          cpus: '0.5'
          memory: 256M
        reservations:
          cpus: '0.1'
          memory: 64M

# 用于Swarm模式的完整资源定义
version: '3.8'
services:
  app:
    image: myapp:latest
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: '1.0'
          memory: 1G
        reservations:
          cpus: '0.5'
          memory: 512M
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3

实战技巧总结

1. 组合使用多个语法特性

x-common-variables: &common-vars
  TZ: Asia/Shanghai
  LANG: en_US.UTF-8

x-base-service: &base-service
  restart: unless-stopped
  logging:
    driver: json-file
    options:
      max-size: "10m"
      max-file: "3"

services:
  api:
    <<: *base-service
    image: dify-api:${API_VERSION:-latest}
    environment:
      <<: *common-vars
      PORT: ${API_PORT:-5001}
    depends_on:
      db:
        condition: service_healthy
    volumes:
      - ./logs:/app/logs
    profiles: ["production"]
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G

2. 环境特定的配置管理

# docker-compose.yml (基础配置)
# docker-compose.override.yml (开发环境)
# docker-compose.prod.yml (生产环境)

# 生产环境配置示例
docker-compose.prod.yml
services:
  api:
    restart: always
    environment:
      - LOG_LEVEL=WARN
    deploy:
      resources:
        limits:
          cpus: '4.0'
          memory: 4G
    profiles: ["production"]

3. 调试与监控配置

# 调试专用服务
services:
  portainer:
    image: portainer/portainer-ce:latest
    profiles: ["debug"]
    ports:
      - "9000:9000"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
  
  adminer:
    image: adminer:latest
    profiles: ["debug"]
    ports:
      - "8080:8080"
    depends_on:
      - db

标题:Docker Compose YAML 用法指南
作者:gitsilence
地址:https://blog.lacknb.cn/articles/2025/07/18/1752803039580.html