docker-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

🚨 CRITICAL GUIDELINES

⚠️ 关键准则

Windows File Path Requirements

Windows文件路径要求

MANDATORY: Always Use Backslashes on Windows for File Paths
When using Edit or Write tools on Windows, you MUST use backslashes (
\
) in file paths, NOT forward slashes (
/
).
Examples:
  • ❌ WRONG:
    D:/repos/project/file.tsx
  • ✅ CORRECT:
    D:\repos\project\file.tsx
This applies to:
  • Edit tool file_path parameter
  • Write tool file_path parameter
  • All file operations on Windows systems
强制要求:在Windows系统中使用文件路径时始终使用反斜杠
在Windows系统上使用编辑或写入工具时,文件路径必须使用反斜杠(
\
),而不是正斜杠(
/
)。
示例:
  • ❌ 错误:
    D:/repos/project/file.tsx
  • ✅ 正确:
    D:\repos\project\file.tsx
此要求适用于:
  • 编辑工具的file_path参数
  • 写入工具的file_path参数
  • Windows系统上的所有文件操作

Documentation Guidelines

文档准则

NEVER create new documentation files unless explicitly requested by the user.
  • Priority: Update existing README.md files rather than creating new documentation
  • Repository cleanliness: Keep repository root clean - only README.md unless user requests otherwise
  • Style: Documentation should be concise, direct, and professional - avoid AI-generated tone
  • User preference: Only create additional .md files when user specifically asks for documentation

除非用户明确要求,否则绝不要创建新的文档文件。
  • 优先级:优先更新现有的README.md文件,而非创建新文档
  • 仓库整洁性:保持仓库根目录整洁 - 除非用户要求,否则只保留README.md
  • 风格:文档应简洁、直接且专业 - 避免AI生成的语气
  • 用户偏好:仅当用户明确要求文档时,才创建额外的.md文件

Docker Best Practices

Docker最佳实践

This skill provides current Docker best practices across all aspects of container development, deployment, and operation.
本技能涵盖容器开发、部署和运维全流程的当前Docker最佳实践。

Image Best Practices

镜像最佳实践

Base Image Selection

基础镜像选择

2025 Recommended Hierarchy:
  1. Wolfi/Chainguard (
    cgr.dev/chainguard/*
    ) - Zero-CVE goal, SBOM included
  2. Alpine (
    alpine:3.19
    ) - ~7MB, minimal attack surface
  3. Distroless (
    gcr.io/distroless/*
    ) - ~2MB, no shell
  4. Slim variants (
    node:20-slim
    ) - ~70MB, balanced
Key rules:
  • Always specify exact version tags:
    node:20.11.0-alpine3.19
  • Never use
    latest
    (unpredictable, breaks reproducibility)
  • Use official images from trusted registries
  • Match base image to actual needs
2025推荐层级:
  1. Wolfi/Chainguard
    cgr.dev/chainguard/*
    )- 零CVE目标,包含SBOM
  2. Alpine
    alpine:3.19
    )- 约7MB,最小攻击面
  3. Distroless
    gcr.io/distroless/*
    )- 约2MB,无Shell
  4. 精简变体
    node:20-slim
    )- 约70MB,平衡型
核心规则:
  • 始终指定精确版本标签:
    node:20.11.0-alpine3.19
  • 绝不使用
    latest
    标签(不可预测,破坏可复现性)
  • 使用可信镜像仓库中的官方镜像
  • 根据实际需求选择基础镜像

Dockerfile Structure

Dockerfile结构

Optimal layer ordering (least to most frequently changing):
dockerfile
1. Base image and system dependencies
2. Application dependencies (package.json, requirements.txt, etc.)
3. Application code
4. Configuration and metadata
Rationale: Docker caches layers. If code changes but dependencies don't, cached dependency layers are reused, speeding up builds.
Example:
dockerfile
FROM python:3.12-slim
最优层顺序(从变更频率最低到最高):
dockerfile
1. 基础镜像和系统依赖
2. 应用依赖(package.json、requirements.txt等)
3. 应用代码
4. 配置和元数据
原理: Docker会缓存镜像层。如果代码变更但依赖未变,可复用已缓存的依赖层,从而加快构建速度。
示例:
dockerfile
FROM python:3.12-slim

1. System packages (rarely change)

1. 系统包(极少变更)

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

2. Dependencies (change occasionally)

2. 依赖(偶尔变更)

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

3. Application code (changes frequently)

3. 应用代码(频繁变更)

COPY . /app WORKDIR /app
CMD ["python", "app.py"]
undefined
COPY . /app WORKDIR /app
CMD ["python", "app.py"]
undefined

Multi-Stage Builds

多阶段构建

Use multi-stage builds to separate build dependencies from runtime:
dockerfile
undefined
使用多阶段构建分离构建依赖与运行时环境:
dockerfile
undefined

Build stage

构建阶段

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

Production stage

生产阶段

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

Only copy what's needed for runtime

仅复制运行时所需内容

COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules USER node CMD ["node", "dist/server.js"]

**Benefits:**
- Smaller final images (no build tools)
- Better security (fewer attack vectors)
- Faster deployment (smaller upload/download)
COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules USER node CMD ["node", "dist/server.js"]

**优势:**
- 最终镜像体积更小(无构建工具)
- 安全性更高(更少攻击向量)
- 部署速度更快(上传/下载体积更小)

Layer Optimization

镜像层优化

Combine commands to reduce layers and image size:
dockerfile
undefined
合并命令以减少镜像层数并缩小体积:
dockerfile
undefined

Bad - 3 layers, cleanup doesn't reduce size

不佳 - 3层,清理操作无法缩小体积

RUN apt-get update RUN apt-get install -y curl RUN rm -rf /var/lib/apt/lists/*
RUN apt-get update RUN apt-get install -y curl RUN rm -rf /var/lib/apt/lists/*

Good - 1 layer, cleanup effective

良好 - 1层,清理操作有效

RUN apt-get update &&
apt-get install -y --no-install-recommends curl &&
rm -rf /var/lib/apt/lists/*
undefined
RUN apt-get update &&
apt-get install -y --no-install-recommends curl &&
rm -rf /var/lib/apt/lists/*
undefined

.dockerignore

.dockerignore

Always create
.dockerignore
to exclude unnecessary files:
undefined
始终创建
.dockerignore
文件以排除不必要的文件:
undefined

Version control

版本控制

.git .gitignore
.git .gitignore

Dependencies

依赖

node_modules pycache *.pyc
node_modules pycache *.pyc

IDE

IDE

.vscode .idea
.vscode .idea

OS

系统

.DS_Store Thumbs.db
.DS_Store Thumbs.db

Logs

日志

*.log logs/
*.log logs/

Testing

测试

coverage/ .nyc_output *.test.js
coverage/ .nyc_output *.test.js

Documentation

文档

README.md docs/
README.md docs/

Environment

环境配置

.env .env.local *.local
undefined
.env .env.local *.local
undefined

Container Runtime Best Practices

容器运行时最佳实践

Security

安全性

bash
docker run \
  # Run as non-root
  --user 1000:1000 \
  # Drop all capabilities, add only needed ones
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  # Read-only filesystem
  --read-only \
  # Temporary writable filesystems
  --tmpfs /tmp:noexec,nosuid \
  # No new privileges
  --security-opt="no-new-privileges:true" \
  # Resource limits
  --memory="512m" \
  --cpus="1.0" \
  my-image
bash
docker run \
  # 以非root用户运行
  --user 1000:1000 \
  # 移除所有权限,仅添加所需权限
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  # 只读文件系统
  --read-only \
  # 临时可写文件系统
  --tmpfs /tmp:noexec,nosuid \
  # 不允许提升权限
  --security-opt="no-new-privileges:true" \
  # 资源限制
  --memory="512m" \
  --cpus="1.0" \
  my-image

Resource Management

资源管理

Always set resource limits in production:
yaml
undefined
在生产环境中始终设置资源限制:
yaml
undefined

docker-compose.yml

docker-compose.yml

services: app: deploy: resources: limits: cpus: '2.0' memory: 1G reservations: cpus: '1.0' memory: 512M
undefined
services: app: deploy: resources: limits: cpus: '2.0' memory: 1G reservations: cpus: '1.0' memory: 512M
undefined

Health Checks

健康检查

Implement health checks for all long-running containers:
dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 --start-period=40s \
  CMD curl -f http://localhost:3000/health || exit 1
Or in compose:
yaml
services:
  app:
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 40s
为所有长期运行的容器实现健康检查:
dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 --start-period=40s \
  CMD curl -f http://localhost:3000/health || exit 1
或在Compose中配置:
yaml
services:
  app:
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 40s

Logging

日志配置

Configure proper logging to prevent disk fill-up:
yaml
services:
  app:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
Or system-wide in
/etc/docker/daemon.json
:
json
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}
配置合理的日志策略以防止磁盘被占满:
yaml
services:
  app:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
或在系统级配置文件
/etc/docker/daemon.json
中设置:
json
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}

Restart Policies

重启策略

yaml
services:
  app:
    # For development
    restart: "no"

    # For production
    restart: unless-stopped

    # Or with fine-grained control (Swarm mode)
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s
yaml
services:
  app:
    # 开发环境
    restart: "no"

    # 生产环境
    restart: unless-stopped

    # 或精细化控制(Swarm模式)
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s

Docker Compose Best Practices

Docker Compose最佳实践

File Structure

文件结构

yaml
undefined
yaml
undefined

No version field needed (Compose v2.40.3+)

Compose v2.40.3+无需version字段

services:

Service definitions

web: # ... api: # ... database: # ...
networks:

Custom networks (preferred)

frontend: backend: internal: true
volumes:

Named volumes (preferred for persistence)

db-data: app-data:
configs:

Configuration files (Swarm mode)

app-config: file: ./config/app.conf
secrets:

Secrets (Swarm mode)

db-password: file: ./secrets/db_pass.txt
undefined
services:

服务定义

web: # ... api: # ... database: # ...
networks:

自定义网络(推荐)

frontend: backend: internal: true
volumes:

命名卷(持久化推荐)

db-data: app-data:
configs:

配置文件(Swarm模式)

app-config: file: ./config/app.conf
secrets:

密钥(Swarm模式)

db-password: file: ./secrets/db_pass.txt
undefined

Network Isolation

网络隔离

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

services:
  web:
    networks:
      - frontend

  api:
    networks:
      - frontend
      - backend

  database:
    networks:
      - backend  # Not accessible from frontend
yaml
networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
    internal: true  # 禁止外部访问

services:
  web:
    networks:
      - frontend

  api:
    networks:
      - frontend
      - backend

  database:
    networks:
      - backend  # 无法从前端网络访问

Environment Variables

环境变量

yaml
services:
  app:
    # Load from file (preferred for non-secrets)
    env_file:
      - .env

    # Inline for service-specific vars
    environment:
      - NODE_ENV=production
      - LOG_LEVEL=info

    # For Swarm mode secrets
    secrets:
      - db_password
Important:
  • Add
    .env
    to
    .gitignore
  • Provide
    .env.example
    as template
  • Never commit secrets to version control
yaml
services:
  app:
    # 从文件加载(非密钥推荐)
    env_file:
      - .env

    # 内联服务特定变量
    environment:
      - NODE_ENV=production
      - LOG_LEVEL=info

    # Swarm模式密钥
    secrets:
      - db_password
重要提示:
  • .env
    添加到
    .gitignore
  • 提供
    .env.example
    作为模板
  • 绝不要将密钥提交到版本控制系统

Dependency Management

依赖管理

yaml
services:
  api:
    depends_on:
      database:
        condition: service_healthy  # Wait for health check
      redis:
        condition: service_started   # Just wait for start
yaml
services:
  api:
    depends_on:
      database:
        condition: service_healthy  # 等待健康检查通过
      redis:
        condition: service_started   # 仅等待启动完成

Production Best Practices

生产环境最佳实践

Image Tagging Strategy

镜像标签策略

bash
undefined
bash
undefined

Use semantic versioning

使用语义化版本

my-app:1.2.3 my-app:1.2 my-app:1 my-app:latest
my-app:1.2.3 my-app:1.2 my-app:1 my-app:latest

Include git commit for traceability

包含Git提交哈希以实现可追溯性

my-app:1.2.3-abc123f
my-app:1.2.3-abc123f

Environment tags

环境标签

my-app:1.2.3-production my-app:1.2.3-staging
undefined
my-app:1.2.3-production my-app:1.2.3-staging
undefined

Secrets Management

密钥管理

Never do this:
dockerfile
undefined
绝不要这样做:
dockerfile
undefined

BAD - secret in layer history

错误 - 密钥会留在镜像层历史中

ENV API_KEY=secret123 RUN echo "password" > /app/config

**Do this:**
```bash
ENV API_KEY=secret123 RUN echo "password" > /app/config

**正确做法:**
```bash

Use Docker secrets (Swarm) or external secret management

使用Docker Secrets(Swarm模式)或外部密钥管理工具

docker secret create db_password ./password.txt
docker secret create db_password ./password.txt

Or mount secrets at runtime

或在运行时挂载密钥

docker run -v /secure/secrets:/run/secrets:ro my-app
docker run -v /secure/secrets:/run/secrets:ro my-app

Or use environment files (not in image)

或使用环境文件(不打包到镜像中)

docker run --env-file /secure/.env my-app
undefined
docker run --env-file /secure/.env my-app
undefined

Monitoring & Observability

监控与可观测性

yaml
services:
  app:
    # Health checks
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s

    # Labels for monitoring tools
    labels:
      - "prometheus.io/scrape=true"
      - "prometheus.io/port=9090"
      - "com.company.team=backend"
      - "com.company.version=1.2.3"

    # Logging
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
yaml
services:
  app:
    # 健康检查
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s

    # 监控工具标签
    labels:
      - "prometheus.io/scrape=true"
      - "prometheus.io/port=9090"
      - "com.company.team=backend"
      - "com.company.version=1.2.3"

    # 日志配置
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

Backup Strategy

备份策略

bash
undefined
bash
undefined

Backup named volume

备份命名卷

docker run --rm
-v VOLUME_NAME:/data
-v $(pwd):/backup
alpine tar czf /backup/backup-$(date +%Y%m%d).tar.gz -C /data .
docker run --rm
-v VOLUME_NAME:/data
-v $(pwd):/backup
alpine tar czf /backup/backup-$(date +%Y%m%d).tar.gz -C /data .

Restore volume

恢复卷

docker run --rm
-v VOLUME_NAME:/data
-v $(pwd):/backup
alpine tar xzf /backup/backup.tar.gz -C /data
undefined
docker run --rm
-v VOLUME_NAME:/data
-v $(pwd):/backup
alpine tar xzf /backup/backup.tar.gz -C /data
undefined

Update Strategy

更新策略

yaml
services:
  app:
    # For Swarm mode - rolling updates
    deploy:
      replicas: 3
      update_config:
        parallelism: 1        # Update 1 at a time
        delay: 10s            # Wait 10s between updates
        failure_action: rollback
        monitor: 60s
      rollback_config:
        parallelism: 1
        delay: 5s
yaml
services:
  app:
    # Swarm模式 - 滚动更新
    deploy:
      replicas: 3
      update_config:
        parallelism: 1        # 每次更新1个实例
        delay: 10s            # 实例更新间隔10秒
        failure_action: rollback
        monitor: 60s
      rollback_config:
        parallelism: 1
        delay: 5s

Platform-Specific Best Practices

平台特定最佳实践

Linux

Linux

  • Use user namespace remapping for added security
  • Leverage native performance advantages
  • Use Alpine for smallest images
  • Configure SELinux/AppArmor profiles
  • Use systemd for Docker daemon management
json
// /etc/docker/daemon.json
{
  "userns-remap": "default",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "live-restore": true
}
  • 使用用户命名空间映射增强安全性
  • 利用原生性能优势
  • 使用Alpine镜像以获得最小体积
  • 配置SELinux/AppArmor配置文件
  • 使用systemd管理Docker守护进程
json
// /etc/docker/daemon.json
{
  "userns-remap": "default",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "live-restore": true
}

macOS

macOS

  • Allocate sufficient resources in Docker Desktop
  • Use
    :delegated
    or
    :cached
    for bind mounts
  • Consider multi-platform builds for ARM (M1/M2)
  • Limit file sharing to necessary directories
yaml
undefined
  • 在Docker Desktop中分配足够的资源
  • 对绑定挂载使用
    :delegated
    :cached
    选项
  • 考虑为ARM架构(M1/M2)进行多平台构建
  • 限制文件共享到必要目录
yaml
undefined

Better volume performance on macOS

macOS平台下更优的卷性能

volumes:
  • ./src:/app/src:delegated # Host writes are delayed
  • ./build:/app/build:cached # Container writes are cached
undefined
volumes:
  • ./src:/app/src:delegated # 主机写入延迟同步
  • ./build:/app/build:cached # 容器写入会被缓存
undefined

Windows

Windows

  • Choose container type: Windows or Linux
  • Use forward slashes in paths
  • Ensure drives are shared in Docker Desktop
  • Be aware of line ending differences (CRLF vs LF)
  • Consider WSL2 backend for better performance
yaml
undefined
  • 选择容器类型:Windows或Linux
  • 在路径中使用正斜杠
  • 确保Docker Desktop中已共享对应驱动器
  • 注意行尾差异(CRLF vs LF)
  • 考虑使用WSL2后端以获得更好性能
yaml
undefined

Windows-compatible paths

Windows兼容路径

volumes:
  • C:/Users/name/app:/app # Forward slashes work

or

  • C:\Users\name\app:/app # Backslashes need escaping in YAML
undefined
volumes:
  • C:/Users/name/app:/app # 正斜杠可正常工作

  • C:\Users\name\app:/app # YAML中反斜杠需要转义
undefined

Performance Best Practices

性能最佳实践

Build Performance

构建性能

bash
undefined
bash
undefined

Use BuildKit (faster, better caching)

使用BuildKit(更快,缓存更优)

export DOCKER_BUILDKIT=1
export DOCKER_BUILDKIT=1

Use cache mounts

使用缓存挂载

RUN --mount=type=cache,target=/root/.cache/pip
pip install -r requirements.txt
RUN --mount=type=cache,target=/root/.cache/pip
pip install -r requirements.txt

Use bind mounts for dependencies

使用绑定挂载管理依赖

RUN --mount=type=bind,source=package.json,target=package.json
--mount=type=bind,source=package-lock.json,target=package-lock.json
--mount=type=cache,target=/root/.npm
npm ci
undefined
RUN --mount=type=bind,source=package.json,target=package.json
--mount=type=bind,source=package-lock.json,target=package-lock.json
--mount=type=cache,target=/root/.npm
npm ci
undefined

Image Size

镜像体积

  • Use multi-stage builds
  • Choose minimal base images
  • Clean up in the same layer
  • Use .dockerignore
  • Remove build dependencies
dockerfile
undefined
  • 使用多阶段构建
  • 选择最小化基础镜像
  • 在同一层中完成清理操作
  • 使用.dockerignore
  • 移除构建依赖
dockerfile
undefined

Install and cleanup in one layer

在同一层中完成安装与清理

RUN apt-get update &&
apt-get install -y --no-install-recommends
package1
package2 &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
undefined
RUN apt-get update &&
apt-get install -y --no-install-recommends
package1
package2 &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
undefined

Runtime Performance

运行时性能

dockerfile
undefined
dockerfile
undefined

Use exec form (no shell overhead)

使用exec格式(无Shell开销)

CMD ["node", "server.js"] # Good
CMD ["node", "server.js"] # 良好

vs

对比

CMD node server.js # Bad - spawns shell
CMD node server.js # 不佳 - 会启动Shell

Optimize signals

优化信号处理

STOPSIGNAL SIGTERM
STOPSIGNAL SIGTERM

Run as non-root (slightly faster, much more secure)

以非root用户运行(略快,安全性大幅提升)

USER appuser
undefined
USER appuser
undefined

Security Best Practices Summary

安全最佳实践总结

Image Security:
  • Use official, minimal base images
  • Scan for vulnerabilities (Docker Scout, Trivy)
  • Don't include secrets in layers
  • Run as non-root user
  • Keep images updated
Runtime Security:
  • Drop capabilities
  • Use read-only filesystem
  • Set resource limits
  • Enable security options
  • Isolate networks
  • Use secrets management
Compliance:
  • Follow CIS Docker Benchmark
  • Implement container scanning in CI/CD
  • Use signed images (Docker Content Trust)
  • Maintain audit logs
  • Regular security reviews
镜像安全:
  • 使用官方、最小化的基础镜像
  • 扫描漏洞(Docker Scout、Trivy)
  • 不要在镜像层中包含密钥
  • 以非root用户运行
  • 保持镜像更新
运行时安全:
  • 移除不必要的权限
  • 使用只读文件系统
  • 设置资源限制
  • 启用安全选项
  • 隔离网络
  • 使用密钥管理工具
合规性:
  • 遵循CIS Docker基准
  • 在CI/CD中实现容器扫描
  • 使用签名镜像(Docker Content Trust)
  • 维护审计日志
  • 定期进行安全审查

Common Anti-Patterns to Avoid

需避免的常见反模式

Don't:
  • Run as root
  • Use
    --privileged
  • Mount Docker socket
  • Use
    latest
    tag
  • Hardcode secrets
  • Skip health checks
  • Ignore resource limits
  • Use huge base images
  • Skip vulnerability scanning
  • Expose unnecessary ports
  • Use inefficient layer caching
  • Commit secrets to Git
Do:
  • Run as non-root
  • Use minimal capabilities
  • Isolate containers
  • Tag with versions
  • Use secrets management
  • Implement health checks
  • Set resource limits
  • Use minimal images
  • Scan regularly
  • Apply least privilege
  • Optimize build cache
  • Use .env.example templates
不要:
  • 以root用户运行
  • 使用
    --privileged
    参数
  • 挂载Docker套接字
  • 使用
    latest
    标签
  • 硬编码密钥
  • 跳过健康检查
  • 忽略资源限制
  • 使用体积庞大的基础镜像
  • 跳过漏洞扫描
  • 暴露不必要的端口
  • 低效使用构建缓存
  • 将密钥提交到Git
应该:
  • 以非root用户运行
  • 使用最小必要权限
  • 隔离容器
  • 使用版本化标签
  • 使用密钥管理工具
  • 实现健康检查
  • 设置资源限制
  • 使用最小化镜像
  • 定期扫描漏洞
  • 遵循最小权限原则
  • 优化构建缓存
  • 使用.env.example模板

Checklist for Production-Ready Images

生产就绪镜像检查清单

  • Based on official, versioned, minimal image
  • Multi-stage build (if applicable)
  • Runs as non-root user
  • No secrets in layers
  • .dockerignore configured
  • Vulnerability scan passed
  • Health check implemented
  • Proper labeling (version, description, etc.)
  • Efficient layer caching
  • Resource limits defined
  • Logging configured
  • Signals handled correctly
  • Security options set
  • Documentation complete
  • Tested on target platform(s)
This skill represents current Docker best practices. Always verify against official documentation for the latest recommendations, as Docker evolves continuously.
  • 基于官方、版本化、最小化镜像
  • 使用多阶段构建(如适用)
  • 以非root用户运行
  • 镜像层中无密钥
  • 已配置.dockerignore
  • 漏洞扫描通过
  • 已实现健康检查
  • 已添加正确标签(版本、描述等)
  • 构建缓存高效
  • 已定义资源限制
  • 已配置日志
  • 信号处理正确
  • 已设置安全选项
  • 文档完整
  • 已在目标平台测试
本技能代表当前的Docker最佳实践。由于Docker持续演进,请始终参考官方文档获取最新建议。