docker-compose-creator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Docker Compose Creator

Docker Compose 多容器应用设计与管理

Design and manage multi-container applications with Docker Compose for both development and production deployments.
使用Docker Compose设计并管理适用于开发和生产环境部署的多容器应用。

When to Use

适用场景

  • Setting up local development environments
  • Defining multi-service application stacks
  • Managing service dependencies
  • Configuring networking between services
  • Environment variable management
  • Production deployments (single host)
  • Testing multi-service interactions
  • 搭建本地开发环境
  • 定义多服务应用栈
  • 管理服务依赖
  • 配置服务间网络
  • 环境变量管理
  • 生产环境部署(单主机)
  • 测试多服务交互

Docker Compose Versions

Docker Compose 版本

VersionReleasedFeaturesUse Case
v3.x2016Service definitions, networksLegacy (avoid for new projects)
v2.x2014Legacy formatNot recommended
v3.142023Full features, modern syntaxCurrent default
Use version
3.14
or later for new projects.
版本发布时间特性适用场景
v3.x2016服务定义、网络旧版本(新项目避免使用)
v2.x2014旧格式不推荐使用
v3.142023全功能、现代语法当前默认版本
新项目请使用
3.14
或更高版本。

Basic Structure

基本结构

yaml
version: '3.14'

services:
  # Service definitions go here

volumes:
  # Named volumes

networks:
  # Custom networks
yaml
version: '3.14'

services:
  # Service definitions go here

volumes:
  # Named volumes

networks:
  # Custom networks

Full-Featured Example: Web Application Stack

完整示例:Web应用栈

yaml
version: '3.14'

services:
  # Frontend (Nginx)
  nginx:
    image: nginx:1.25-alpine
    container_name: webapp-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
    depends_on:
      - api
    networks:
      - frontend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s

  # API Server (Node.js)
  api:
    build:
      context: ./api
      dockerfile: Dockerfile
      target: production
    container_name: webapp-api
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=postgres
      - REDIS_HOST=redis
      - LOG_LEVEL=info
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started
    networks:
      - frontend
      - backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

  # PostgreSQL Database
  postgres:
    image: postgres:15-alpine
    container_name: webapp-db
    environment:
      - POSTGRES_DB=myapp
      - POSTGRES_USER=appuser
      - POSTGRES_PASSWORD=${DB_PASSWORD:?Database password required}
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
    networks:
      - backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U appuser -d myapp"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

  # Redis Cache
  redis:
    image: redis:7-alpine
    container_name: webapp-cache
    command: redis-server --requirepass ${REDIS_PASSWORD:?Redis password required}
    volumes:
      - redis_data:/data
    networks:
      - backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

  # Background Worker (Optional)
  worker:
    build:
      context: ./worker
      dockerfile: Dockerfile
    container_name: webapp-worker
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=postgres
      - REDIS_HOST=redis
    depends_on:
      - postgres
      - redis
    networks:
      - backend
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:

networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
yaml
version: '3.14'

services:
  # Frontend (Nginx)
  nginx:
    image: nginx:1.25-alpine
    container_name: webapp-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
    depends_on:
      - api
    networks:
      - frontend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s

  # API Server (Node.js)
  api:
    build:
      context: ./api
      dockerfile: Dockerfile
      target: production
    container_name: webapp-api
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=postgres
      - REDIS_HOST=redis
      - LOG_LEVEL=info
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started
    networks:
      - frontend
      - backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

  # PostgreSQL Database
  postgres:
    image: postgres:15-alpine
    container_name: webapp-db
    environment:
      - POSTGRES_DB=myapp
      - POSTGRES_USER=appuser
      - POSTGRES_PASSWORD=${DB_PASSWORD:?Database password required}
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
    networks:
      - backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U appuser -d myapp"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

  # Redis Cache
  redis:
    image: redis:7-alpine
    container_name: webapp-cache
    command: redis-server --requirepass ${REDIS_PASSWORD:?Redis password required}
    volumes:
      - redis_data:/data
    networks:
      - backend
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

  # Background Worker (Optional)
  worker:
    build:
      context: ./worker
      dockerfile: Dockerfile
    container_name: webapp-worker
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=postgres
      - REDIS_HOST=redis
    depends_on:
      - postgres
      - redis
    networks:
      - backend
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:

networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge

Service Configuration

服务配置

Image vs Build

预构建镜像 vs 从Dockerfile构建

yaml
undefined
yaml
undefined

Using pre-built image

Using pre-built image

services: app: image: myregistry/myapp:1.0.0
services: app: image: myregistry/myapp:1.0.0

Building from Dockerfile

Building from Dockerfile

services: app: build: ./app
services: app: build: ./app

Advanced build options

Advanced build options

services: app: build: context: ./app dockerfile: Dockerfile.prod args: - BUILD_ENV=production target: production
undefined
services: app: build: context: ./app dockerfile: Dockerfile.prod args: - BUILD_ENV=production target: production
undefined

Environment Variables

环境变量

yaml
undefined
yaml
undefined

Method 1: Inline

Method 1: Inline

services: api: environment: - NODE_ENV=production - LOG_LEVEL=info
services: api: environment: - NODE_ENV=production - LOG_LEVEL=info

Method 2: From file

Method 2: From file

services: api: env_file: - .env - .env.${ENVIRONMENT}
services: api: env_file: - .env - .env.${ENVIRONMENT}

Method 3: Mixed (with required variable check)

Method 3: Mixed (with required variable check)

services: api: environment: - DATABASE_PASSWORD=${DB_PASSWORD:?Database password required} - DATABASE_HOST=postgres
undefined
services: api: environment: - DATABASE_PASSWORD=${DB_PASSWORD:?Database password required} - DATABASE_HOST=postgres
undefined

Resource Limits

资源限制

yaml
services:
  api:
    # Memory: 512MB max, 256MB soft limit
    mem_limit: 512m
    memswap_limit: 1g

    # CPU: 1 core
    cpus: '1.0'

    # File descriptor limit
    ulimits:
      nofile:
        soft: 65536
        hard: 65536
yaml
services:
  api:
    # Memory: 512MB max, 256MB soft limit
    mem_limit: 512m
    memswap_limit: 1g

    # CPU: 1 core
    cpus: '1.0'

    # File descriptor limit
    ulimits:
      nofile:
        soft: 65536
        hard: 65536

Restart Policy

重启策略

yaml
services:
  api:
    restart: unless-stopped  # Restart unless manually stopped
    # Options: no, always, unless-stopped, on-failure

  worker:
    restart: on-failure
    restart_policy:
      condition: on-failure
      delay: 5s
      max_attempts: 3
      window: 60s
yaml
services:
  api:
    restart: unless-stopped  # Restart unless manually stopped
    # Options: no, always, unless-stopped, on-failure

  worker:
    restart: on-failure
    restart_policy:
      condition: on-failure
      delay: 5s
      max_attempts: 3
      window: 60s

Networking

网络配置

Service Discovery

服务发现

yaml
services:
  api:
    networks:
      - backend
    environment:
      # Access postgres by service name on backend network
      - DATABASE_HOST=postgres

  postgres:
    networks:
      - backend
yaml
services:
  api:
    networks:
      - backend
    environment:
      # Access postgres by service name on backend network
      - DATABASE_HOST=postgres

  postgres:
    networks:
      - backend

Multi-Network Setup

多网络配置

yaml
services:
  api:
    networks:
      - frontend  # Can talk to nginx
      - backend   # Can talk to postgres

  nginx:
    networks:
      - frontend  # Can talk to api

  postgres:
    networks:
      - backend   # Can talk to api, worker

networks:
  frontend:
  backend:
yaml
services:
  api:
    networks:
      - frontend  # Can talk to nginx
      - backend   # Can talk to postgres

  nginx:
    networks:
      - frontend  # Can talk to api

  postgres:
    networks:
      - backend   # Can talk to api, worker

networks:
  frontend:
  backend:

Port Mapping

端口映射

yaml
services:
  api:
    ports:
      - "3000:3000"           # Map container 3000 to host 3000
      - "3001:3000"           # Map container 3000 to host 3001
      - "127.0.0.1:3000:3000" # Bind to localhost only
yaml
services:
  api:
    ports:
      - "3000:3000"           # Map container 3000 to host 3000
      - "3001:3000"           # Map container 3000 to host 3001
      - "127.0.0.1:3000:3000" # Bind to localhost only

Volumes

数据卷

Named Volumes

命名数据卷

yaml
services:
  postgres:
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:
yaml
services:
  postgres:
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Bind Mounts

绑定挂载

yaml
services:
  api:
    volumes:
      # Host path : Container path
      - ./src:/app/src
      # Read-only
      - ./config:/app/config:ro
      # With options
      - ./logs:/app/logs:delegated
yaml
services:
  api:
    volumes:
      # Host path : Container path
      - ./src:/app/src
      # Read-only
      - ./config:/app/config:ro
      # With options
      - ./logs:/app/logs:delegated

Tmpfs (Memory-backed)

Tmpfs(内存挂载)

yaml
services:
  api:
    tmpfs:
      - /tmp
      - /run
yaml
services:
  api:
    tmpfs:
      - /tmp
      - /run

Depends On

服务依赖

Basic Dependency

基础依赖

yaml
services:
  api:
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:15

  redis:
    image: redis:7
yaml
services:
  api:
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:15

  redis:
    image: redis:7

Conditional Dependency (Health Checks)

条件依赖(健康检查)

yaml
services:
  api:
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started

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

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

Health Checks

健康检查

yaml
services:
  api:
    healthcheck:
      # Check command
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]

      # Check interval
      interval: 30s

      # Timeout per check
      timeout: 5s

      # Retries before failure
      retries: 3

      # Wait before first check
      start_period: 10s
yaml
services:
  api:
    healthcheck:
      # Check command
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]

      # Check interval
      interval: 30s

      # Timeout per check
      timeout: 5s

      # Retries before failure
      retries: 3

      # Wait before first check
      start_period: 10s

Logging

日志配置

yaml
services:
  api:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
        labels: "service=api"

  # Syslog
  worker:
    logging:
      driver: "syslog"
      options:
        syslog-address: "udp://127.0.0.1:514"
        tag: "{{.Name}}"
yaml
services:
  api:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
        labels: "service=api"

  # Syslog
  worker:
    logging:
      driver: "syslog"
      options:
        syslog-address: "udp://127.0.0.1:514"
        tag: "{{.Name}}"

Development vs Production

开发环境 vs 生产环境

Development (docker-compose.yml)

开发环境(docker-compose.yml)

yaml
version: '3.14'

services:
  api:
    build: ./api
    ports:
      - "3000:3000"
    volumes:
      - ./api/src:/app/src  # Hot reload
    environment:
      - NODE_ENV=development
    command: npm run dev
yaml
version: '3.14'

services:
  api:
    build: ./api
    ports:
      - "3000:3000"
    volumes:
      - ./api/src:/app/src  # Hot reload
    environment:
      - NODE_ENV=development
    command: npm run dev

Production (docker-compose.prod.yml)

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

yaml
version: '3.14'

services:
  api:
    image: myregistry/myapp:1.0.0
    restart: unless-stopped
    environment:
      - NODE_ENV=production
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 5s
      retries: 3
yaml
version: '3.14'

services:
  api:
    image: myregistry/myapp:1.0.0
    restart: unless-stopped
    environment:
      - NODE_ENV=production
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 5s
      retries: 3

Running with Override

使用覆盖配置启动

bash
undefined
bash
undefined

Development

Development

docker compose up
docker compose up

Production

Production

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

Common Commands

常用命令

bash
undefined
bash
undefined

Start services

Start services

docker compose up
docker compose up

Start in background

Start in background

docker compose up -d
docker compose up -d

Stop services

Stop services

docker compose down
docker compose down

Stop without removing volumes

Stop without removing volumes

docker compose stop
docker compose stop

Remove containers, networks, volumes

Remove containers, networks, volumes

docker compose down -v
docker compose down -v

View logs

View logs

docker compose logs -f
docker compose logs -f

Specific service logs

Specific service logs

docker compose logs -f api
docker compose logs -f api

Execute command in service

Execute command in service

docker compose exec api npm test
docker compose exec api npm test

Run one-off command

Run one-off command

docker compose run api npm test
docker compose run api npm test

View service status

View service status

docker compose ps
docker compose ps

Rebuild images

Rebuild images

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

Remove and rebuild

Remove and rebuild

docker compose down --rmi all && docker compose up --build
undefined
docker compose down --rmi all && docker compose up --build
undefined

Advanced Patterns

高级模式

Service Override

服务覆盖配置

yaml
undefined
yaml
undefined

docker-compose.override.yml (git-ignored)

docker-compose.override.yml (git-ignored)

services: api: volumes: - ./src:/app/src # Local development environment: - DEBUG=true
undefined
services: api: volumes: - ./src:/app/src # Local development environment: - DEBUG=true
undefined

Multiple Configurations

多配置文件组合

bash
undefined
bash
undefined

Production with monitoring

Production with monitoring

docker compose
-f docker-compose.yml
-f docker-compose.prod.yml
-f docker-compose.monitoring.yml
up -d
undefined
docker compose
-f docker-compose.yml
-f docker-compose.prod.yml
-f docker-compose.monitoring.yml
up -d
undefined

Environment-Specific Files

环境专属配置文件

bash
undefined
bash
undefined

Load .env.${ENVIRONMENT}

Load .env.${ENVIRONMENT}

docker compose --env-file .env.production up -d
undefined
docker compose --env-file .env.production up -d
undefined

Production Deployment Checklist

生产环境部署检查清单

  • All services have healthchecks
  • Services use
    restart: unless-stopped
  • Sensitive data in
    .env
    (git-ignored)
  • Volumes for persistent data
  • Resource limits set
  • Logging configured
  • Networks isolated
  • Use specific image tags (never
    latest
    )
  • Test with
    docker compose up -d && docker compose ps
  • 所有服务配置健康检查
  • 服务使用
    restart: unless-stopped
    策略
  • 敏感数据存储在
    .env
    文件中(已加入git忽略)
  • 使用数据卷存储持久化数据
  • 设置资源限制
  • 配置日志收集
  • 网络隔离
  • 使用特定镜像标签(绝不使用
    latest
  • 通过
    docker compose up -d && docker compose ps
    测试

Troubleshooting

故障排查

bash
undefined
bash
undefined

Check service status

Check service status

docker compose ps
docker compose ps

View detailed service info

View detailed service info

docker compose exec postgres psql -U user -c "\l"
docker compose exec postgres psql -U user -c "\l"

Network diagnosis

Network diagnosis

docker compose exec api ping postgres
docker compose exec api ping postgres

Resource usage

Resource usage

docker stats
docker stats

Rebuild and restart

Rebuild and restart

docker compose down --rmi local docker compose up --build
undefined
docker compose down --rmi local docker compose up --build
undefined

References

参考资料