Docker Compose 文件主要包含 6 个部分,其中 services 是核心,其他部分用于定义网络、存储、配置、密钥等资源。通过这些部分,你可以完整地定义一个多容器应用的运行环境。

📁 Docker Compose 文件的 6 个部分

序号

名称

说明

是否必须

1

version

指定 Docker Compose 文件的版本(如3.8

❌(v2+ 可省略)

2

services

定义应用中的各个服务(容器)

✅ 必需

3

networks

定义自定义网络(供服务间通信)

❌(可选)

4

volumes

定义命名卷(用于数据持久化)

❌(可选)

5

configs

定义配置文件(用于服务配置)

❌(可选,v3.3+)

6

secrets

定义密钥(如密码、证书等)

❌(可选,v3.1+)

1. 版本声明 (version)

version: '3.8'  # 指定 Compose 文件格式版本

2. 服务定义 (services)

services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./html:/usr/share/nginx/html
  
  database:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: password
    volumes:
      - db_data:/var/lib/mysql

3. 卷定义 (volumes)

volumes:
  db_data:
    driver: local
  shared_volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /host/path

4. 网络定义 (networks)

networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
    internal: true  # 内部网络,不能访问外网

5. 定义配置文件(configs

定义配置文件(如配置、证书),服务可以挂载这些配置

configs:
  app_config:
    file: ./app.conf

服务中使用:

services:
  web:
    configs:
      - source: app_config
        target: /etc/app.conf

6. 密钥管理 (secrets)

secrets:
  db_password:
    file: ./secrets/db_password.txt
  api_key:
    environment: API_KEY

📦 示例:完整的 docker-compose.yml

version: '3.8'  # 1. 版本

services:       # 2. 服务(必需)
  web:
    image: nginx:latest
    ports:
      - "80:80"
    networks:
      - frontend
    volumes:
      - ./html:/usr/share/nginx/html
    configs:
      - source: app_config
        target: /etc/app.conf
    secrets:
      - db_password
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_password
    volumes:
      - db_data:/var/lib/mysql
    networks:
      - backend

networks:       # 3. 网络
  frontend:
    driver: bridge
  backend:
    driver: bridge

volumes:        # 4. 卷
  db_data:

configs:        # 5. 配置
  app_config:
    file: ./app.conf

secrets:        # 6. 密钥
  db_password:
    file: ./db_password.txt