docker-compose

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Docker Compose

Docker Compose

Orchestrate multi-container applications with declarative YAML configuration.
使用声明式YAML配置编排多容器应用。

When to Use This Skill

何时使用此技能

Use this skill when:
  • Running multi-container applications locally
  • Setting up development environments
  • Defining service dependencies and networking
  • Managing application stacks with multiple services
  • Creating reproducible development setups
在以下场景使用此技能:
  • 在本地运行多容器应用
  • 搭建开发环境
  • 定义服务依赖与网络配置
  • 管理包含多个服务的应用栈
  • 创建可复现的开发环境

Prerequisites

前置条件

  • Docker Engine with Compose plugin (v2)
  • Basic Docker knowledge
  • YAML syntax understanding
  • 带有Compose插件(v2版本)的Docker Engine
  • 基础Docker知识
  • 了解YAML语法

Basic Configuration

基础配置

Simple Application Stack

简单应用栈

yaml
undefined
yaml
undefined

docker-compose.yml

docker-compose.yml

version: '3.8'
services: web: build: . ports: - "3000:3000" environment: - NODE_ENV=development - DATABASE_URL=postgres://postgres:secret@db:5432/myapp depends_on: - db - redis
db: image: postgres:15-alpine environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: secret POSTGRES_DB: myapp volumes: - postgres-data:/var/lib/postgresql/data ports: - "5432:5432"
redis: image: redis:7-alpine ports: - "6379:6379"
volumes: postgres-data:
undefined
version: '3.8'
services: web: build: . ports: - "3000:3000" environment: - NODE_ENV=development - DATABASE_URL=postgres://postgres:secret@db:5432/myapp depends_on: - db - redis
db: image: postgres:15-alpine environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: secret POSTGRES_DB: myapp volumes: - postgres-data:/var/lib/postgresql/data ports: - "5432:5432"
redis: image: redis:7-alpine ports: - "6379:6379"
volumes: postgres-data:
undefined

Service Configuration

服务配置

Build Options

构建选项

yaml
services:
  app:
    build:
      context: ./app
      dockerfile: Dockerfile.dev
      args:
        NODE_VERSION: "20"
      target: development
      cache_from:
        - myapp:cache
    image: myapp:dev
yaml
services:
  app:
    build:
      context: ./app
      dockerfile: Dockerfile.dev
      args:
        NODE_VERSION: "20"
      target: development
      cache_from:
        - myapp:cache
    image: myapp:dev

Environment Variables

环境变量

yaml
services:
  app:
    environment:
      - NODE_ENV=production
      - API_KEY=${API_KEY}  # From shell or .env file
    env_file:
      - .env
      - .env.local
yaml
services:
  app:
    environment:
      - NODE_ENV=production
      - API_KEY=${API_KEY}  # 来自Shell或.env文件
    env_file:
      - .env
      - .env.local

Port Mapping

端口映射

yaml
services:
  web:
    ports:
      - "3000:3000"           # HOST:CONTAINER
      - "127.0.0.1:9229:9229" # Bind to localhost only
      - "8080-8090:8080-8090" # Port range
    expose:
      - "3000"                # Internal only (no host binding)
yaml
services:
  web:
    ports:
      - "3000:3000"           # 主机:容器
      - "127.0.0.1:9229:9229" # 仅绑定到本地主机
      - "8080-8090:8080-8090" # 端口范围
    expose:
      - "3000"                # 仅内部访问(不绑定主机)

Volume Mounts

卷挂载

yaml
services:
  app:
    volumes:
      # Named volume
      - app-data:/app/data
      # Bind mount
      - ./src:/app/src
      # Read-only bind mount
      - ./config:/app/config:ro
      # Anonymous volume (for node_modules)
      - /app/node_modules

volumes:
  app-data:
    driver: local
yaml
services:
  app:
    volumes:
      # 命名卷
      - app-data:/app/data
      # 绑定挂载
      - ./src:/app/src
      # 只读绑定挂载
      - ./config:/app/config:ro
      # 匿名卷(用于node_modules)
      - /app/node_modules

volumes:
  app-data:
    driver: local

Dependencies

依赖配置

yaml
services:
  web:
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

  db:
    image: postgres:15
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5
yaml
services:
  web:
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

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

Networking

网络配置

Custom Networks

自定义网络

yaml
services:
  frontend:
    networks:
      - frontend-net

  backend:
    networks:
      - frontend-net
      - backend-net

  db:
    networks:
      - backend-net

networks:
  frontend-net:
    driver: bridge
  backend-net:
    driver: bridge
    internal: true  # No external access
yaml
services:
  frontend:
    networks:
      - frontend-net

  backend:
    networks:
      - frontend-net
      - backend-net

  db:
    networks:
      - backend-net

networks:
  frontend-net:
    driver: bridge
  backend-net:
    driver: bridge
    internal: true  # 禁止外部访问

Network Aliases

网络别名

yaml
services:
  db:
    networks:
      backend:
        aliases:
          - database
          - postgres

networks:
  backend:
yaml
services:
  db:
    networks:
      backend:
        aliases:
          - database
          - postgres

networks:
  backend:

Resource Limits

资源限制

yaml
services:
  app:
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 1G
        reservations:
          cpus: '0.5'
          memory: 256M
yaml
services:
  app:
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 1G
        reservations:
          cpus: '0.5'
          memory: 256M

Multiple Compose Files

多Compose文件

Override Files

覆盖文件

yaml
undefined
yaml
undefined

docker-compose.yml (base)

docker-compose.yml(基础配置)

services: web: image: myapp:latest ports: - "3000:3000"
services: web: image: myapp:latest ports: - "3000:3000"

docker-compose.override.yml (development - auto-loaded)

docker-compose.override.yml(开发环境 - 自动加载)

services: web: build: . volumes: - ./src:/app/src environment: - DEBUG=true
services: web: build: . volumes: - ./src:/app/src environment: - DEBUG=true

docker-compose.prod.yml (production)

docker-compose.prod.yml(生产环境)

services: web: deploy: replicas: 3 environment: - DEBUG=false
undefined
services: web: deploy: replicas: 3 environment: - DEBUG=false
undefined

Using Multiple Files

使用多文件

bash
undefined
bash
undefined

Development (uses override automatically)

开发环境(自动使用override文件)

docker compose up
docker compose up

Production

生产环境

docker compose -f docker-compose.yml -f docker-compose.prod.yml up
docker compose -f docker-compose.yml -f docker-compose.prod.yml up

Merge and view final config

合并并查看最终配置

docker compose -f docker-compose.yml -f docker-compose.prod.yml config
undefined
docker compose -f docker-compose.yml -f docker-compose.prod.yml config
undefined

Profiles

配置文件

yaml
services:
  web:
    image: myapp

  db:
    image: postgres:15

  debug:
    image: busybox
    profiles:
      - debug

  monitoring:
    image: prometheus
    profiles:
      - monitoring
bash
undefined
yaml
services:
  web:
    image: myapp

  db:
    image: postgres:15

  debug:
    image: busybox
    profiles:
      - debug

  monitoring:
    image: prometheus
    profiles:
      - monitoring
bash
undefined

Run without profiles (web, db only)

不使用配置文件启动(仅启动web、db)

docker compose up
docker compose up

Run with debug profile

使用debug配置文件启动

docker compose --profile debug up
docker compose --profile debug up

Run with multiple profiles

使用多个配置文件启动

docker compose --profile debug --profile monitoring up
undefined
docker compose --profile debug --profile monitoring up
undefined

Commands

常用命令

Lifecycle

生命周期管理

bash
undefined
bash
undefined

Start services

启动服务(后台运行)

docker compose up -d
docker compose up -d

Start specific service

启动指定服务

docker compose up -d web
docker compose up -d web

Stop services

停止服务

docker compose stop
docker compose stop

Stop and remove containers

停止并移除容器

docker compose down
docker compose down

Stop and remove everything including volumes

停止并移除所有资源(包括卷)

docker compose down -v --rmi all
docker compose down -v --rmi all

Restart services

重启指定服务

docker compose restart web
undefined
docker compose restart web
undefined

Building

构建相关

bash
undefined
bash
undefined

Build images

构建镜像

docker compose build
docker compose build

Build without cache

不使用缓存构建

docker compose build --no-cache
docker compose build --no-cache

Build and start

构建并启动服务

docker compose up --build
docker compose up --build

Pull latest images

拉取最新镜像

docker compose pull
undefined
docker compose pull
undefined

Monitoring

监控相关

bash
undefined
bash
undefined

View logs

查看日志(实时输出)

docker compose logs -f
docker compose logs -f

View specific service logs

查看指定服务日志

docker compose logs -f web
docker compose logs -f web

View running services

查看运行中的服务

docker compose ps
docker compose ps

View resource usage

查看资源使用情况

docker compose top
undefined
docker compose top
undefined

Execution

执行命令

bash
undefined
bash
undefined

Run command in new container

在新容器中运行命令(执行后移除容器)

docker compose run --rm web npm test
docker compose run --rm web npm test

Execute in running container

在运行中的容器中执行命令

docker compose exec web /bin/sh
docker compose exec web /bin/sh

Scale service

扩展服务实例数量

docker compose up -d --scale worker=3
undefined
docker compose up -d --scale worker=3
undefined

Development Workflow

开发工作流

Watch Mode (Compose v2.22+)

监听模式(Compose v2.22+)

yaml
services:
  web:
    build: .
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: ./package.json
bash
docker compose watch
yaml
services:
  web:
    build: .
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: ./package.json
bash
docker compose watch

Hot Reload Setup

热重载配置

yaml
services:
  web:
    build:
      context: .
      target: development
    volumes:
      - ./src:/app/src
      - /app/node_modules
    environment:
      - CHOKIDAR_USEPOLLING=true
    command: npm run dev
yaml
services:
  web:
    build:
      context: .
      target: development
    volumes:
      - ./src:/app/src
      - /app/node_modules
    environment:
      - CHOKIDAR_USEPOLLING=true
    command: npm run dev

Common Patterns

常见模式

Database Initialization

数据库初始化

yaml
services:
  db:
    image: postgres:15
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
    environment:
      POSTGRES_DB: myapp
yaml
services:
  db:
    image: postgres:15
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
    environment:
      POSTGRES_DB: myapp

Reverse Proxy

反向代理

yaml
services:
  proxy:
    image: traefik:v3.0
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./traefik.yml:/etc/traefik/traefik.yml:ro

  web:
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.web.rule=Host(`app.localhost`)"
yaml
services:
  proxy:
    image: traefik:v3.0
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./traefik.yml:/etc/traefik/traefik.yml:ro

  web:
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.web.rule=Host(`app.localhost`)"

Common Issues

常见问题

Issue: Container Cannot Resolve Service Name

问题:容器无法解析服务名称

Problem: Service can't connect to another service by name Solution: Ensure services are on the same network, check depends_on
问题描述:服务无法通过名称连接到其他服务 解决方案:确保服务处于同一网络,检查depends_on配置

Issue: Volume Permissions

问题:卷权限不足

Problem: Container can't write to mounted volume Solution: Match container user UID with host, or use named volumes
问题描述:容器无法写入挂载的卷 解决方案:使容器用户UID与主机匹配,或使用命名卷

Issue: Port Already in Use

问题:端口已被占用

Problem: Error binding to port Solution: Change host port or stop conflicting service
问题描述:绑定端口时出现错误 解决方案:修改主机端口或停止占用该端口的服务

Issue: Changes Not Reflected

问题:修改未同步到容器

Problem: Code changes don't appear in container Solution: Check volume mounts, rebuild if Dockerfile changed
问题描述:代码修改未在容器中体现 解决方案:检查卷挂载配置,若Dockerfile有修改则重新构建

Best Practices

最佳实践

  • Use named volumes for persistent data
  • Define healthchecks for database dependencies
  • Use profiles to separate optional services
  • Keep secrets in .env files (not committed)
  • Use override files for environment-specific config
  • Pin image versions for reproducibility
  • Use networks to isolate service groups
  • Leverage watch mode for development
  • 使用命名卷存储持久化数据
  • 为数据库依赖定义健康检查
  • 使用配置文件分离可选服务
  • 将密钥存储在.env文件中(不要提交到版本库)
  • 使用覆盖文件配置环境特定参数
  • 固定镜像版本以保证可复现性
  • 使用网络隔离服务组
  • 利用监听模式提升开发效率

Related Skills

相关技能

  • docker-management - Docker fundamentals
  • kubernetes-ops - Production orchestration
  • reverse-proxy - Production routing
  • docker-management - Docker基础
  • kubernetes-ops - 生产环境编排
  • reverse-proxy - 生产环境路由