dockerfile-optimise

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dockerfile Optimization Best Practices

Dockerfile优化最佳实践

Comprehensive Dockerfile optimization guide sourced exclusively from official Docker documentation. Contains 48 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
本指南是完全源自Docker官方文档的Dockerfile优化综合指南,包含8个类别下的48条规则,按影响优先级排序,可指导自动化重构和代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new Dockerfiles or modifying existing ones
  • Optimizing Docker build times (layer caching, cache mounts, context management)
  • Reducing Docker image size (multi-stage builds, minimal base images)
  • Hardening container security (secret mounts, non-root users, attestations)
  • Setting up CI/CD pipelines with Docker builds
  • Reviewing Dockerfiles for anti-patterns
在以下场景中参考本指南:
  • 编写新的Dockerfile或修改现有Dockerfile
  • 优化Docker构建时间(分层缓存、缓存挂载、上下文管理)
  • 减小Docker镜像大小(多阶段构建、最小基础镜像)
  • 加固容器安全性(密钥挂载、非root用户、证明机制)
  • 搭建包含Docker构建的CI/CD流水线
  • 审查Dockerfile中的反模式

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Layer Caching & OrderingCRITICAL
cache-
2Multi-Stage BuildsCRITICAL
stage-
3Base Image SelectionHIGH
base-
4Build Context ManagementHIGH
ctx-
5Security & SecretsHIGH
sec-
6Dependency ManagementMEDIUM-HIGH
dep-
7Instruction PatternsMEDIUM
inst-
8Quality & ValidationMEDIUM
lint-
优先级类别影响程度前缀
1分层缓存与顺序关键
cache-
2多阶段构建关键
stage-
3基础镜像选择
base-
4构建上下文管理
ctx-
5安全与密钥
sec-
6依赖管理中高
dep-
7指令模式
inst-
8质量与验证
lint-

Quick Reference

快速参考

1. Layer Caching & Ordering (CRITICAL)

1. 分层缓存与顺序(关键)

  • cache-layer-order
    - Order layers by change frequency
  • cache-copy-deps-first
    - Copy dependency files before source code
  • cache-copy-link
    - Use COPY --link for cache-efficient layer copying
  • cache-mount-package
    - Use cache mounts for package managers
  • cache-apt-combine
    - Combine apt-get update with install
  • cache-external
    - Use external cache for CI/CD builds
  • cache-invalidation
    - Avoid unnecessary cache invalidation
  • cache-minimize-layers
    - Consolidate related RUN instructions
  • cache-layer-order
    - 按变更频率对分层排序
  • cache-copy-deps-first
    - 先复制依赖文件再复制源代码
  • cache-copy-link
    - 使用COPY --link实现缓存高效的分层复制
  • cache-mount-package
    - 为包管理器使用缓存挂载
  • cache-apt-combine
    - 将apt-get update与install合并执行
  • cache-external
    - 为CI/CD构建使用外部缓存
  • cache-invalidation
    - 避免不必要的缓存失效
  • cache-minimize-layers
    - 合并相关的RUN指令

2. Multi-Stage Builds (CRITICAL)

2. 多阶段构建(关键)

  • stage-separate-build-runtime
    - Separate build and runtime stages
  • stage-named-stages
    - Use named build stages
  • stage-parallel-branches
    - Exploit parallel stage execution
  • stage-target-builds
    - Use target builds for dev/prod
  • stage-copy-artifacts-only
    - Copy only final artifacts between stages
  • stage-reusable-base
    - Create reusable base stages
  • stage-separate-build-runtime
    - 分离构建阶段与运行时阶段
  • stage-named-stages
    - 使用命名构建阶段
  • stage-parallel-branches
    - 利用并行阶段执行
  • stage-target-builds
    - 为开发/生产环境使用目标构建
  • stage-copy-artifacts-only
    - 仅在阶段间复制最终产物
  • stage-reusable-base
    - 创建可复用的基础阶段

3. Base Image Selection (HIGH)

3. 基础镜像选择(高)

  • base-minimal-image
    - Use minimal base images
  • base-official-images
    - Use Docker Official Images
  • base-pin-versions
    - Pin base image versions with digests
  • base-arg-version
    - Use ARG before FROM to parameterize base images
  • base-rebuild-regularly
    - Rebuild images regularly with --pull
  • base-distroless
    - Use distroless or scratch images for production
  • base-minimal-image
    - 使用最小化基础镜像
  • base-official-images
    - 使用Docker官方镜像
  • base-pin-versions
    - 使用摘要固定基础镜像版本
  • base-arg-version
    - 在FROM前使用ARG参数化基础镜像
  • base-rebuild-regularly
    - 定期使用--pull参数重新构建镜像
  • base-distroless
    - 生产环境使用distroless或scratch镜像

4. Build Context Management (HIGH)

4. 构建上下文管理(高)

  • ctx-dockerignore
    - Use .dockerignore to exclude unnecessary files
  • ctx-bind-mounts
    - Use bind mounts instead of COPY for build-only files
  • ctx-minimize-context
    - Keep build context small
  • ctx-syntax-directive
    - Use syntax directive for latest BuildKit features (prerequisite for cache mounts, secret mounts, heredocs, COPY --link)
  • ctx-dockerignore
    - 使用.dockerignore排除不必要的文件
  • ctx-bind-mounts
    - 为仅构建文件使用绑定挂载而非COPY
  • ctx-minimize-context
    - 减小构建上下文体积
  • ctx-syntax-directive
    - 使用语法指令启用最新BuildKit功能(缓存挂载、密钥挂载、here文档、COPY --link的前提条件)

5. Security & Secrets (HIGH)

5. 安全与密钥(高)

  • sec-secret-mounts
    - Use secret mounts for sensitive data
  • sec-non-root-user
    - Run as non-root user
  • sec-no-secrets-in-args
    - Never pass secrets via ARG or ENV
  • sec-ssh-mounts
    - Use SSH mounts for private repository access
  • sec-attestations
    - Enable SBOM and provenance attestations
  • sec-no-unnecessary-packages
    - Avoid installing unnecessary packages
  • sec-ephemeral-containers
    - Design ephemeral, stateless containers
  • sec-secret-mounts
    - 为敏感数据使用密钥挂载
  • sec-non-root-user
    - 以非root用户运行容器
  • sec-no-secrets-in-args
    - 绝不要通过ARG或ENV传递密钥
  • sec-ssh-mounts
    - 为私有仓库访问使用SSH挂载
  • sec-attestations
    - 启用SBOM和来源证明
  • sec-no-unnecessary-packages
    - 避免安装不必要的包
  • sec-ephemeral-containers
    - 设计临时、无状态的容器

6. Dependency Management (MEDIUM-HIGH)

6. 依赖管理(中高)

  • dep-cache-mount-apt
    - Use cache mount for apt package manager
  • dep-cache-mount-npm
    - Use cache mount for npm, yarn, and pnpm
  • dep-cache-mount-pip
    - Use cache mount for pip
  • dep-version-pin
    - Pin package versions for reproducibility
  • dep-cleanup-caches
    - Clean package manager caches in the same layer
  • dep-cache-mount-apt
    - 为apt包管理器使用缓存挂载
  • dep-cache-mount-npm
    - 为npm、yarn和pnpm使用缓存挂载
  • dep-cache-mount-pip
    - 为pip使用缓存挂载
  • dep-version-pin
    - 固定包版本以保证可复现性
  • dep-cleanup-caches
    - 在同一分层中清理包管理器缓存

7. Instruction Patterns (MEDIUM)

7. 指令模式(中)

  • inst-json-cmd
    - Use JSON form for CMD and ENTRYPOINT
  • inst-healthcheck
    - Define HEALTHCHECK for container orchestration
  • inst-heredoc-scripts
    - Use heredocs for multi-line scripts
  • inst-entrypoint-exec
    - Use exec in entrypoint scripts
  • inst-workdir-absolute
    - Use absolute paths with WORKDIR
  • inst-copy-over-add
    - Prefer COPY over ADD
  • inst-json-cmd
    - 为CMD和ENTRYPOINT使用JSON格式
  • inst-healthcheck
    - 为容器编排定义HEALTHCHECK
  • inst-heredoc-scripts
    - 为多行脚本使用here文档
  • inst-entrypoint-exec
    - 在入口脚本中使用exec
  • inst-workdir-absolute
    - 为WORKDIR使用绝对路径
  • inst-copy-over-add
    - 优先使用COPY而非ADD

8. Quality & Validation (MEDIUM)

8. 质量与验证(中)

  • lint-build-checks
    - Enable Docker build checks
  • lint-pipefail
    - Use pipefail for piped RUN commands
  • lint-labels
    - Use standard labels for image metadata
  • lint-sort-arguments
    - Sort multi-line arguments alphabetically
  • lint-single-concern
    - One concern per container
  • lint-build-checks
    - 启用Docker构建检查
  • lint-pipefail
    - 为管道化RUN命令使用pipefail
  • lint-labels
    - 为镜像元数据使用标准标签
  • lint-sort-arguments
    - 按字母顺序排序多行参数
  • lint-single-concern
    - 每个容器仅处理一个关注点

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响等级
  • 规则模板 - 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md类别定义与排序
assets/templates/_template.md新规则模板
metadata.json版本与参考信息