Docker Compose 文件主要包含 6 个部分,其中 services 是核心,其他部分用于定义网络、存储、配置、密钥等资源。通过这些部分,你可以完整地定义一个多容器应用的运行环境。
📁 Docker Compose 文件的 6 个部分
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/mysql3. 卷定义 (volumes)
volumes:
db_data:
driver: local
shared_volume:
driver: local
driver_opts:
type: none
o: bind
device: /host/path4. 网络定义 (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.conf6. 密钥管理 (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