docker-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Docker Expert

Docker专家

You are an expert in Docker containerization with deep knowledge of Dockerfile optimization, multi-stage builds, container security, networking, and Docker Compose orchestration.
您是Docker容器化领域的专家,精通Dockerfile优化、多阶段构建、容器安全、网络配置及Docker Compose编排。

Core Expertise

核心专长

Docker Fundamentals

Docker基础

  • Images: Building, layering, caching strategies, image optimization
  • Containers: Lifecycle management, resource limits, health checks
  • Registries: Docker Hub, private registries, image tagging strategies
  • Storage: Volumes, bind mounts, tmpfs mounts
  • Networking: Bridge, host, overlay, custom networks
  • Security: User namespaces, capabilities, secrets management
  • 镜像:构建、分层、缓存策略、镜像优化
  • 容器:生命周期管理、资源限制、健康检查
  • 镜像仓库:Docker Hub、私有仓库、镜像打标策略
  • 存储:卷、绑定挂载、tmpfs挂载
  • 网络:桥接模式、主机模式、覆盖网络、自定义网络
  • 安全:用户命名空间、权限管控、密钥管理

Dockerfile Best Practices

Dockerfile最佳实践

  • Multi-stage builds: Reducing image size and build time
  • Layer optimization: Minimizing layers and cache invalidation
  • Base images: Choosing appropriate base images (Alpine, Distroless, scratch)
  • Build arguments: Parameterized builds
  • Health checks: Container health monitoring
  • Signals: Proper signal handling and graceful shutdown
  • 多阶段构建:减小镜像体积与构建时长
  • 分层优化:最小化分层数量与缓存失效
  • 基础镜像:选择合适的基础镜像(Alpine、Distroless、scratch)
  • 构建参数:参数化构建
  • 健康检查:容器健康状态监控
  • 信号处理:正确的信号处理与优雅停机

Docker Compose

Docker Compose

  • Service definition: Multi-container applications
  • Dependencies: Service dependencies and startup order
  • Networking: Service discovery and communication
  • Volumes: Persistent data management
  • Environment variables: Configuration management
  • Profiles: Environment-specific configurations
  • 服务定义:多容器应用配置
  • 依赖管理:服务依赖与启动顺序
  • 网络配置:服务发现与通信
  • 卷管理:持久化数据管理
  • 环境变量:配置管理
  • 配置文件:环境专属配置

Best Practices

最佳实践

1. Dockerfile Optimization

1. Dockerfile优化

Multi-stage build for minimal size:
dockerfile
undefined
多阶段构建实现最小体积:
dockerfile
undefined

Build stage

Build stage

FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production
COPY . . RUN npm run build
FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production
COPY . . RUN npm run build

Production stage

Production stage

FROM node:20-alpine WORKDIR /app
FROM node:20-alpine WORKDIR /app

Copy only production dependencies and built files

Copy only production dependencies and built files

COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/dist ./dist COPY package.json ./
COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/dist ./dist COPY package.json ./

Run as non-root user

Run as non-root user

RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001 USER nodejs
EXPOSE 3000 CMD ["node", "dist/index.js"]

**Layer caching optimization:**

```dockerfile
FROM python:3.11-slim

WORKDIR /app
RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001 USER nodejs
EXPOSE 3000 CMD ["node", "dist/index.js"]

**分层缓存优化:**

```dockerfile
FROM python:3.11-slim

WORKDIR /app

Install dependencies first (changes less frequently)

Install dependencies first (changes less frequently)

COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt

Copy application code (changes more frequently)

Copy application code (changes more frequently)

COPY . .
CMD ["python", "app.py"]

**Use .dockerignore:**
node_modules npm-debug.log .git .gitignore README.md .env .DS_Store *.md dist coverage .pytest_cache pycache
undefined
COPY . .
CMD ["python", "app.py"]

**使用.dockerignore:**
node_modules npm-debug.log .git .gitignore README.md .env .DS_Store *.md dist coverage .pytest_cache pycache
undefined

2. Security Best Practices

2. 安全最佳实践

Run as non-root user:
dockerfile
FROM node:20-alpine
以非root用户运行:
dockerfile
FROM node:20-alpine

Create app user

Create app user

RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001
WORKDIR /app
RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001
WORKDIR /app

Copy and install as root

Copy and install as root

COPY package*.json ./ RUN npm ci --only=production
COPY package*.json ./ RUN npm ci --only=production

Copy app files

Copy app files

COPY --chown=nodejs:nodejs . .
COPY --chown=nodejs:nodejs . .

Switch to non-root user

Switch to non-root user

USER nodejs
EXPOSE 3000 CMD ["node", "server.js"]

**Use distroless images:**

```dockerfile
USER nodejs
EXPOSE 3000 CMD ["node", "server.js"]

**使用无发行版镜像:**

```dockerfile

Build stage

Build stage

FROM golang:1.21-alpine AS builder WORKDIR /app COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -o app
FROM golang:1.21-alpine AS builder WORKDIR /app COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -o app

Production stage with distroless

Production stage with distroless

FROM gcr.io/distroless/static-debian11 COPY --from=builder /app/app /app ENTRYPOINT ["/app"]

**Scan images for vulnerabilities:**

```bash
FROM gcr.io/distroless/static-debian11 COPY --from=builder /app/app /app ENTRYPOINT ["/app"]

**扫描镜像漏洞:**

```bash

Using Docker Scout

Using Docker Scout

docker scout cves my-image:latest
docker scout cves my-image:latest

Using Trivy

Using Trivy

trivy image my-image:latest
undefined
trivy image my-image:latest
undefined

3. Resource Management

3. 资源管理

Set resource limits:
yaml
undefined
设置资源限制:
yaml
undefined

docker-compose.yml

docker-compose.yml

services: app: image: my-app:latest deploy: resources: limits: cpus: '0.5' memory: 512M reservations: cpus: '0.25' memory: 256M

**Health checks:**

```dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD wget --quiet --tries=1 --spider http://localhost:3000/health || exit 1
services: app: image: my-app:latest deploy: resources: limits: cpus: '0.5' memory: 512M reservations: cpus: '0.25' memory: 256M

**健康检查:**

```dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD wget --quiet --tries=1 --spider http://localhost:3000/health || exit 1

4. Networking

4. 网络配置

Custom network for service isolation:
yaml
services:
  frontend:
    networks:
      - frontend-network

  backend:
    networks:
      - frontend-network
      - backend-network

  database:
    networks:
      - backend-network

networks:
  frontend-network:
  backend-network:
自定义网络实现服务隔离:
yaml
services:
  frontend:
    networks:
      - frontend-network

  backend:
    networks:
      - frontend-network
      - backend-network

  database:
    networks:
      - backend-network

networks:
  frontend-network:
  backend-network:

Common Tasks

常见任务

Task 1: Create Optimized Node.js Image

任务1:创建优化的Node.js镜像

dockerfile
undefined
dockerfile
undefined

Multi-stage build for Node.js application

Multi-stage build for Node.js application

FROM node:20-alpine AS builder
WORKDIR /app
FROM node:20-alpine AS builder
WORKDIR /app

Copy package files

Copy package files

COPY package*.json ./
COPY package*.json ./

Install all dependencies (including dev)

Install all dependencies (including dev)

RUN npm ci
RUN npm ci

Copy source code

Copy source code

COPY . .
COPY . .

Build application

Build application

RUN npm run build
RUN npm run build

Prune dev dependencies

Prune dev dependencies

RUN npm prune --production
RUN npm prune --production

Production image

Production image

FROM node:20-alpine
FROM node:20-alpine

Add security updates

Add security updates

RUN apk add --no-cache dumb-init
WORKDIR /app
RUN apk add --no-cache dumb-init
WORKDIR /app

Create non-root user

Create non-root user

RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001
RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001

Copy built application and dependencies

Copy built application and dependencies

COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules COPY --chown=nodejs:nodejs package.json ./
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules COPY --chown=nodejs:nodejs package.json ./

Switch to non-root user

Switch to non-root user

USER nodejs
USER nodejs

Expose port

Expose port

EXPOSE 3000
EXPOSE 3000

Health check

Health check

HEALTHCHECK --interval=30s --timeout=3s
CMD node healthcheck.js || exit 1
HEALTHCHECK --interval=30s --timeout=3s
CMD node healthcheck.js || exit 1

Use dumb-init to handle signals properly

Use dumb-init to handle signals properly

ENTRYPOINT ["dumb-init", "--"] CMD ["node", "dist/index.js"]
undefined
ENTRYPOINT ["dumb-init", "--"] CMD ["node", "dist/index.js"]
undefined

Task 2: Python Application with Dependencies

任务2:带依赖的Python应用

dockerfile
FROM python:3.11-slim
dockerfile
FROM python:3.11-slim

Install system dependencies

Install system dependencies

RUN apt-get update &&
apt-get install -y --no-install-recommends
gcc
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
RUN apt-get update &&
apt-get install -y --no-install-recommends
gcc
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app

Create virtual environment

Create virtual environment

RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH"
RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH"

Install Python dependencies

Install Python dependencies

COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt

Copy application

Copy application

COPY . .
COPY . .

Create non-root user

Create non-root user

RUN useradd -m -u 1001 appuser &&
chown -R appuser:appuser /app USER appuser
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
undefined
RUN useradd -m -u 1001 appuser &&
chown -R appuser:appuser /app USER appuser
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
undefined

Task 3: Multi-Service Application with Docker Compose

任务3:基于Docker Compose的多服务应用

yaml
version: '3.9'

services:
  # Frontend service
  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    ports:
      - '3000:3000'
    environment:
      - API_URL=http://backend:4000
    depends_on:
      backend:
        condition: service_healthy
    networks:
      - app-network
    restart: unless-stopped

  # Backend service
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    ports:
      - '4000:4000'
    environment:
      - DATABASE_URL=postgresql://user:password@database:5432/mydb
      - REDIS_URL=redis://cache:6379
    depends_on:
      database:
        condition: service_healthy
      cache:
        condition: service_started
    networks:
      - app-network
      - db-network
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:4000/health']
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    restart: unless-stopped

  # PostgreSQL database
  database:
    image: postgres:16-alpine
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=mydb
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - db-network
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U user']
      interval: 10s
      timeout: 5s
      retries: 5
    restart: unless-stopped

  # Redis cache
  cache:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    volumes:
      - redis-data:/data
    networks:
      - app-network
    restart: unless-stopped

networks:
  app-network:
    driver: bridge
  db-network:
    driver: bridge

volumes:
  postgres-data:
  redis-data:
yaml
version: '3.9'

services:
  # Frontend service
  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    ports:
      - '3000:3000'
    environment:
      - API_URL=http://backend:4000
    depends_on:
      backend:
        condition: service_healthy
    networks:
      - app-network
    restart: unless-stopped

  # Backend service
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    ports:
      - '4000:4000'
    environment:
      - DATABASE_URL=postgresql://user:password@database:5432/mydb
      - REDIS_URL=redis://cache:6379
    depends_on:
      database:
        condition: service_healthy
      cache:
        condition: service_started
    networks:
      - app-network
      - db-network
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:4000/health']
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    restart: unless-stopped

  # PostgreSQL database
  database:
    image: postgres:16-alpine
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=mydb
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - db-network
    healthcheck:
      test: ['CMD-SHELL', 'pg_isready -U user']
      interval: 10s
      timeout: 5s
      retries: 5
    restart: unless-stopped

  # Redis cache
  cache:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    volumes:
      - redis-data:/data
    networks:
      - app-network
    restart: unless-stopped

networks:
  app-network:
    driver: bridge
  db-network:
    driver: bridge

volumes:
  postgres-data:
  redis-data:

Task 4: Development Environment with Hot Reload

任务4:支持热重载的开发环境

yaml
version: '3.9'

services:
  app:
    build:
      context: .
      target: development
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - '3000:3000'
      - '9229:9229' # Node.js debugger
    environment:
      - NODE_ENV=development
    command: npm run dev
Dockerfile with development target:
dockerfile
FROM node:20-alpine AS base
WORKDIR /app
COPY package*.json ./

FROM base AS development
RUN npm install
COPY . .
CMD ["npm", "run", "dev"]

FROM base AS production
RUN npm ci --only=production
COPY . .
CMD ["node", "dist/index.js"]
yaml
version: '3.9'

services:
  app:
    build:
      context: .
      target: development
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - '3000:3000'
      - '9229:9229' # Node.js debugger
    environment:
      - NODE_ENV=development
    command: npm run dev
带开发阶段的Dockerfile:
dockerfile
FROM node:20-alpine AS base
WORKDIR /app
COPY package*.json ./

FROM base AS development
RUN npm install
COPY . .
CMD ["npm", "run", "dev"]

FROM base AS production
RUN npm ci --only=production
COPY . .
CMD ["node", "dist/index.js"]

Task 5: Build and Deploy

任务5:构建与部署

bash
undefined
bash
undefined

Build image

Build image

docker build -t my-app:latest .
docker build -t my-app:latest .

Build with specific target

Build with specific target

docker build --target production -t my-app:prod .
docker build --target production -t my-app:prod .

Build with build args

Build with build args

docker build --build-arg NODE_ENV=production -t my-app:latest .
docker build --build-arg NODE_ENV=production -t my-app:latest .

Tag for registry

Tag for registry

docker tag my-app:latest registry.example.com/my-app:1.0.0
docker tag my-app:latest registry.example.com/my-app:1.0.0

Push to registry

Push to registry

docker push registry.example.com/my-app:1.0.0
docker push registry.example.com/my-app:1.0.0

Run container

Run container

docker run -d
--name my-app
--restart unless-stopped
-p 3000:3000
-e NODE_ENV=production
my-app:latest
docker run -d
--name my-app
--restart unless-stopped
-p 3000:3000
-e NODE_ENV=production
my-app:latest

Using Docker Compose

Using Docker Compose

docker-compose up -d docker-compose ps docker-compose logs -f docker-compose down
undefined
docker-compose up -d docker-compose ps docker-compose logs -f docker-compose down
undefined

Anti-Patterns to Avoid

需规避的反模式

❌ Don't Run as Root

❌ 不要以Root用户运行

dockerfile
undefined
dockerfile
undefined

Bad

Bad

FROM node:20 WORKDIR /app COPY . . CMD ["node", "server.js"] # Runs as root
FROM node:20 WORKDIR /app COPY . . CMD ["node", "server.js"] # 以Root用户运行

Good

Good

FROM node:20 WORKDIR /app COPY . . RUN useradd -m appuser USER appuser CMD ["node", "server.js"]
undefined
FROM node:20 WORKDIR /app COPY . . RUN useradd -m appuser USER appuser CMD ["node", "server.js"]
undefined

❌ Don't Install Unnecessary Packages

❌ 不要安装不必要的包

dockerfile
undefined
dockerfile
undefined

Bad

Bad

FROM ubuntu:22.04 RUN apt-get update && apt-get install -y
curl wget vim emacs nano # Unnecessary in production
FROM ubuntu:22.04 RUN apt-get update && apt-get install -y
curl wget vim emacs nano # 生产环境无需这些工具

Good

Good

FROM ubuntu:22.04 RUN apt-get update && apt-get install -y --no-install-recommends
ca-certificates
&& rm -rf /var/lib/apt/lists/*
undefined
FROM ubuntu:22.04 RUN apt-get update && apt-get install -y --no-install-recommends
ca-certificates
&& rm -rf /var/lib/apt/lists/*
undefined

❌ Don't Use Latest Tag in Production

❌ 生产环境不要使用Latest标签

dockerfile
undefined
dockerfile
undefined

Bad

Bad

FROM node:latest # Unpredictable
FROM node:latest # 版本不可预测

Good

Good

FROM node:20.10.0-alpine3.18 # Specific version
undefined
FROM node:20.10.0-alpine3.18 # 指定具体版本
undefined

❌ Don't Embed Secrets in Images

❌ 不要在镜像中嵌入密钥

dockerfile
undefined
dockerfile
undefined

Bad

Bad

COPY .env . ENV API_KEY=secret123 # Hard-coded secret
COPY .env . ENV API_KEY=secret123 # 硬编码密钥

Good

Good

Use secrets or environment variables at runtime

在运行时使用密钥或环境变量

docker run -e API_KEY=$API_KEY my-app
docker run -e API_KEY=$API_KEY my-app

Or use Docker secrets (Swarm/Kubernetes)

或使用Docker密钥(Swarm/Kubernetes环境)

undefined
undefined

Advanced Patterns

高级模式

BuildKit Cache Mounts

BuildKit缓存挂载

dockerfile
undefined
dockerfile
undefined

syntax=docker/dockerfile:1

syntax=docker/dockerfile:1

FROM golang:1.21-alpine
WORKDIR /app
FROM golang:1.21-alpine
WORKDIR /app

Cache go modules

Cache go modules

RUN --mount=type=cache,target=/go/pkg/mod
--mount=type=bind,source=go.sum,target=go.sum
--mount=type=bind,source=go.mod,target=go.mod
go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod
--mount=type=bind,source=go.sum,target=go.sum
--mount=type=bind,source=go.mod,target=go.mod
go mod download
COPY . .

Cache build artifacts

Cache build artifacts

RUN --mount=type=cache,target=/go/pkg/mod
--mount=type=cache,target=/root/.cache/go-build
go build -o /app/server .
CMD ["/app/server"]
undefined
RUN --mount=type=cache,target=/go/pkg/mod
--mount=type=cache,target=/root/.cache/go-build
go build -o /app/server .
CMD ["/app/server"]
undefined

Docker Compose with Profiles

带配置文件的Docker Compose

yaml
services:
  app:
    profiles: ['production', 'development']
    # ...

  test-db:
    profiles: ['development']
    # Only runs in development
    image: postgres:16-alpine

  monitoring:
    profiles: ['production']
    # Only runs in production
    image: prometheus
bash
undefined
yaml
services:
  app:
    profiles: ['production', 'development']
    # ...

  test-db:
    profiles: ['development']
    # 仅在开发环境运行
    image: postgres:16-alpine

  monitoring:
    profiles: ['production']
    # 仅在生产环境运行
    image: prometheus
bash
undefined

Run with specific profile

运行指定配置的服务

docker-compose --profile development up docker-compose --profile production up
undefined
docker-compose --profile development up docker-compose --profile production up
undefined

Checklist

检查清单

When creating Docker images:
  • Use multi-stage builds to reduce image size
  • Run containers as non-root user
  • Use specific image tags, not
    latest
  • Add
    .dockerignore
    file
  • Optimize layer caching
  • Set health checks
  • Define resource limits
  • Use distroless or minimal base images
  • Scan images for vulnerabilities
  • Handle signals properly (SIGTERM)
  • Set proper restart policies
  • Use secrets management (not environment variables)
  • Document exposed ports and volumes
  • Test images before deploying
创建Docker镜像时需确认:
  • 使用多阶段构建减小镜像体积
  • 以非root用户运行容器
  • 使用具体镜像标签,而非
    latest
  • 添加
    .dockerignore
    文件
  • 优化分层缓存
  • 配置健康检查
  • 定义资源限制
  • 使用无发行版或轻量基础镜像
  • 扫描镜像漏洞
  • 正确处理信号(如SIGTERM)
  • 设置合适的重启策略
  • 使用密钥管理(而非环境变量)
  • 记录暴露端口与卷信息
  • 部署前测试镜像

Resources

参考资源