🐳 每个开发人员都应该知道的 10 个 Docker 最佳实践 - 附示例!

Docker Best Practices

由于容器化在现代开发中变得至关重要,以下是实际实现的基本 Docker 实践:

  • 使用多阶段构建
  • # Build stage
    FROM node:16 AS builder
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    COPY . .
    RUN npm run build
    
    # Production stage
    FROM node:16-slim
    COPY --from=builder /app/dist /app
    EXPOSE 3000
    CMD ["node", "app"]

    结果:生产图像尺寸减少了高达 90%!

  • 利用 .dockerignore
  • node_modules
    npm-debug.log
    Dockerfile
    .git
    .env
    *.md

    通过排除不必要的文件来保持您的构建清洁和安全。

  • 选择特定的基础图像标签
  • # ❌ Bad practice
    FROM node:latest
    
    # ✅ Good practice
    FROM node:16.17.0-alpine3.16

    确保跨环境的一致性并防止意外中断。

  • 一个容器,一个进程
  • # ✅ Good practice
    FROM nginx:alpine
    COPY ./web-app /usr/share/nginx/html
    # Single process: nginx
    CMD ["nginx", "-g", "daemon off;"]
  • 优化层缓存
  • # ✅ Good practice
    COPY package.json package-lock.json ./
    RUN npm install
    # Source code changes don't trigger node_modules reinstall
    COPY . .
  • 使用非 root 用户
  • FROM node:16-alpine
    # Create app directory and user
    RUN mkdir /app && addgroup -S appgroup && adduser -S appuser -G appgroup
    WORKDIR /app
    # Switch to non-root user
    USER appuser
    COPY --chown=appuser:appgroup . .
  • 扫描漏洞
  • # Using Trivy in CI/CD
    trivy image your-image:tag

    在您的管道中设置自动扫描以确保持续的安全。

  • 保持图像最少
  • # ✅ Good practice: Using alpine
    FROM python:3.9-alpine
    RUN apk add --no-cache postgresql-libs
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
  • 明智地缓存依赖项
  • # ✅ Good practice
    COPY package.json yarn.lock ./
    RUN yarn install --frozen-lockfile
    COPY . .
  • 设置资源限制
  • # Docker run with limits
    docker run -d \
      --name myapp \
      --memory="512m" \
      --cpus="1.0" \
      your-image:tag

    Docker Compose 版本:

    services:
      web:
        image: your-image:tag
        deploy:
          resources:
            limits:
              cpus: '1.0'
              memory: 512M

    🔍 福利:环境变量最佳实践

    # ❌ Bad practice: Hardcoding
    ENV API_KEY=1234567890
    
    # ✅ Good practice: Using ARG for build-time variables
    ARG BUILD_VERSION
    ENV APP_VERSION=$BUILD_VERSION
    
    # ✅ Better practice: Using docker-compose.yml
    # docker-compose.yml
    services:
      app:
        env_file:
          - .env.production

    💡 专业提示:始终为你的 Docker 设置维护清晰的文档:

    # Service Name
    ## Build
    `docker build -t service-name .`
    
    ## Run
    `docker run -p 3000:3000 service-name`
    
    ## Environment Variables
    - `PORT`: Application port (default: 3000)
    - `NODE_ENV`: Runtime environment
    
    ## Resource Requirements
    - Memory: 512MB minimum
    - CPU: 1 core recommended

    哪些 Docker 实践改善了您的开发工作流程?在下面分享您的经验!