dockerfile-validator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDockerfile Validator
Dockerfile 验证工具
Overview
概述
Comprehensive toolkit for validating Dockerfiles with syntax checking, security scanning, best practices enforcement, and build optimization analysis. This skill uses a single self-contained script () that handles everything: tool installation, validation, and cleanup.
dockerfile-validate.shKey Features:
- ✅ Single script execution - no dependencies on other scripts
- ✅ Auto-installs hadolint and Checkov in Python venvs if not found
- ✅ Runs all 4 validation stages (syntax, security, best practices, optimization)
- ✅ Auto-cleanup on exit using bash trap (success or failure)
- ✅ Zero configuration required
一款集语法检查、安全扫描、最佳实践执行和构建优化分析于一体的Dockerfile综合验证工具。该工具使用一个独立的自包含脚本()处理所有操作:工具安装、验证和清理。
dockerfile-validate.sh核心特性:
- ✅ 单脚本执行 - 不依赖其他脚本
- ✅ 若未检测到hadolint和Checkov,会自动在Python虚拟环境中安装
- ✅ 运行全部4个验证阶段(语法、安全、最佳实践、优化)
- ✅ 使用bash trap在退出时自动清理(无论成功或失败)
- ✅ 无需任何配置
When to Use This Skill
使用场景
Invoke this skill when:
- Validating Dockerfile syntax and structure
- Checking Dockerfiles for security vulnerabilities
- Optimizing Docker image build performance
- Ensuring adherence to official Docker best practices
- Debugging Dockerfile errors or build issues
- Performing security audits of container images
- The user asks to "validate", "lint", "check", or "optimize" a Dockerfile
- Reviewing Dockerfiles before committing to version control
- Analyzing existing Dockerfiles for improvements
在以下场景中调用该工具:
- 验证Dockerfile的语法和结构
- 检查Dockerfile中的安全漏洞
- 优化Docker镜像的构建性能
- 确保遵循官方Docker最佳实践
- 调试Dockerfile错误或构建问题
- 对容器镜像执行安全审计
- 用户要求“验证”“检查(lint)”“检测”或“优化”Dockerfile时
- 提交到版本控制前审核Dockerfile
- 分析现有Dockerfile以寻找改进空间
Do NOT Use This Skill For
不适用场景
- Generating new Dockerfiles (use dockerfile-generator instead)
- Building or running containers (use docker build/run commands)
- Debugging running containers (use docker logs, docker exec)
- Managing Docker images or registries
- 生成新的Dockerfile(请使用dockerfile-generator工具)
- 构建或运行容器(请使用docker build/run命令)
- 调试运行中的容器(请使用docker logs、docker exec)
- 管理Docker镜像或镜像仓库
Quick Start
快速开始
Single command to validate any Dockerfile:
bash
bash scripts/dockerfile-validate.sh DockerfileThat's it! The script automatically:
- Checks if hadolint and Checkov are installed
- Installs them temporarily in Python venvs if needed
- Runs all 4 validation stages (syntax, security, best practices, optimization)
- Cleans up temporary installations on exit
验证任意Dockerfile的单条命令:
bash
bash scripts/dockerfile-validate.sh Dockerfile就是这么简单!脚本会自动:
- 检查hadolint和Checkov是否已安装
- 若未安装,会临时在Python虚拟环境中安装它们
- 运行全部4个验证阶段(语法、安全、最佳实践、优化)
- 退出时清理临时安装的工具
Validation Workflow
验证流程
The script runs a comprehensive 4-stage validation:
dockerfile-validate.sh┌─────────────────────────────────────────────────────────┐
│ Auto-Install (if needed) │
│ ├─> Check for hadolint and Checkov │
│ ├─> Install in Python venvs if not found │
│ └─> Set TEMP_INSTALL=true (triggers cleanup on exit) │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [1/4] Syntax Validation (hadolint) │
│ ├─> Dockerfile syntax checking │
│ ├─> Instruction validation │
│ ├─> Shell script validation (via ShellCheck) │
│ └─> 100+ built-in linting rules │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [2/4] Security Scan (Checkov) │
│ ├─> Security policy validation │
│ ├─> Hardcoded secret detection │
│ ├─> Port exposure checks │
│ ├─> USER directive validation │
│ └─> 50+ security policies │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [3/4] Best Practices Validation (custom) │
│ ├─> Base image tag validation (:latest check) │
│ ├─> USER directive enforcement (non-root) │
│ ├─> HEALTHCHECK presence │
│ ├─> Layer efficiency (RUN command count) │
│ ├─> Package cache cleanup verification │
│ ├─> Hardcoded secrets detection │
│ └─> COPY ordering for build cache efficiency │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [4/4] Optimization Analysis (custom) │
│ ├─> Base image size analysis (Alpine suggestions) │
│ ├─> Multi-stage build opportunities │
│ ├─> Layer count optimization │
│ ├─> .dockerignore file check │
│ └─> Build structure recommendations │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ Auto-Cleanup (bash trap - always runs) │
│ └─> Remove temp venvs if TEMP_INSTALL=true │
└─────────────────────────────────────────────────────────┘Cleanup Guarantee:
Uses to ensure cleanup runs on:
trap cleanup EXIT INT TERM- ✅ Normal exit
- ✅ Validation failure
- ✅ Ctrl+C (interrupt)
- ✅ Script error
dockerfile-validate.sh┌─────────────────────────────────────────────────────────┐
│ 自动安装(若需要) │
│ ├─> 检测hadolint和Checkov是否存在 │
│ ├─> 若未找到,在Python虚拟环境中安装 │
│ └─> 设置TEMP_INSTALL=true(触发退出时的清理操作) │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [1/4] 语法验证(基于hadolint) │
│ ├─> Dockerfile语法检查 │
│ ├─> 指令验证 │
│ ├─> Shell脚本验证(通过ShellCheck) │
│ └─> 100+内置检查规则 │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [2/4] 安全扫描(基于Checkov) │
│ ├─> 安全策略验证 │
│ ├─> 硬编码密钥检测 │
│ ├─> 端口暴露检查 │
│ ├─> USER指令验证 │
│ └─> 50+安全策略 │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [3/4] 最佳实践验证(自定义规则) │
│ ├─> 基础镜像标签验证(检查:latest标签) │
│ ├─> USER指令强制执行(非root用户) │
│ ├─> HEALTHCHECK指令存在性检查 │
│ ├─> 分层效率(RUN命令数量) │
│ ├─> 包缓存清理验证 │
│ ├─> 硬编码密钥检测 │
│ └─> 为构建缓存效率优化COPY指令顺序 │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ [4/4] 优化分析(自定义规则) │
│ ├─> 基础镜像大小分析(推荐使用Alpine镜像) │
│ ├─> 多阶段构建机会识别 │
│ ├─> 分层数量优化 │
│ ├─> .dockerignore文件检查 │
│ └─> 构建结构建议 │
└─────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────┐
│ 自动清理(bash trap - 始终运行) │
│ └─> 若TEMP_INSTALL=true则删除临时虚拟环境 │
└─────────────────────────────────────────────────────────┘清理保障:
使用确保在以下场景中自动运行清理:
trap cleanup EXIT INT TERM- ✅ 正常退出
- ✅ 验证失败
- ✅ Ctrl+C(中断)
- ✅ 脚本错误
Core Capabilities
核心功能
1. Syntax Validation with hadolint
1. 基于hadolint的语法验证
Purpose: Lint Dockerfile syntax and catch common mistakes before building.
Tool: hadolint - A Dockerfile linter that validates instructions and embedded bash commands using ShellCheck.
Installation:
Tools are automatically installed by the validation script if not found. For permanent installation:
bash
undefined目标: 在构建前检查Dockerfile语法,捕获常见错误。
工具: hadolint - 一款Dockerfile代码检查工具,通过ShellCheck验证指令和嵌入的bash命令。
安装方式:
若未找到工具,验证脚本会自动安装。如需永久安装:
bash
undefinedmacOS
macOS
brew install hadolint
brew install hadolint
Linux
Linux
wget -O ~/.local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64
chmod +x ~/.local/bin/hadolint
wget -O ~/.local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64
chmod +x ~/.local/bin/hadolint
Docker (fallback option)
Docker(备选方案)
docker pull hadolint/hadolint
**Workflow:**
```bashdocker pull hadolint/hadolint
**使用流程:**
```bashRun hadolint on Dockerfile
对Dockerfile运行hadolint
hadolint Dockerfile
hadolint Dockerfile
Run with JSON output for parsing
以JSON格式输出结果用于解析
hadolint --format json Dockerfile
hadolint --format json Dockerfile
Run with specific rules ignored
忽略特定规则运行
hadolint --ignore DL3006 --ignore DL3008 Dockerfile
hadolint --ignore DL3006 --ignore DL3008 Dockerfile
Using Docker if not installed
若未安装,使用Docker运行
docker run --rm -i hadolint/hadolint < Dockerfile
**Common Issues Detected:**
**DL-prefixed rules (hadolint-specific):**
- `DL3000` - Use absolute WORKDIR paths
- `DL3001` - For some bash commands make no sense in a Docker container
- `DL3002` - Last USER should not be root
- `DL3003` - Use WORKDIR to switch directories
- `DL3004` - Do not use sudo
- `DL3006` - Always tag image versions (avoid :latest)
- `DL3007` - Using latest is not recommended
- `DL3008` - Pin versions in apt-get install
- `DL3009` - Delete apt-cache after installing
- `DL3013` - Pin versions in pip install
- `DL3014` - Use -y switch for apt-get
- `DL3015` - Avoid additional packages with apt-get
- `DL3016` - Pin versions in npm install
- `DL3018` - Pin versions in apk add
- `DL3019` - Use --no-cache with apk add
- `DL3020` - Use COPY instead of ADD for files
- `DL3021` - COPY from previous stages should reference by name
- `DL3022` - COPY --from should reference a previously defined FROM alias
- `DL3025` - Use JSON notation for CMD and ENTRYPOINT
- `DL3059` - Multiple consecutive RUN instructions (combine for layer efficiency)
**SC-prefixed rules (ShellCheck for RUN commands):**
- `SC1091` - Not following sourced files
- `SC2046` - Quote to prevent word splitting
- `SC2086` - Double quote to prevent globbing
- `SC2164` - Use cd ... || exit for error handling
**Rule Severity Levels:**
- **error** - Will likely cause build failure or runtime issues
- **warning** - Violates best practices, should be fixed
- **info** - Suggestions for improvement
- **style** - Code style preferences
**Best Practices:**
- Run hadolint before every docker build
- Integrate into CI/CD pipelines
- Configure .hadolint.yaml for project-specific rules
- Address errors before warnings
- Use inline ignore comments sparingly with justificationdocker run --rm -i hadolint/hadolint < Dockerfile
**检测到的常见问题:**
**DL前缀规则(hadolint专属):**
- `DL3000` - 使用绝对路径作为WORKDIR
- `DL3001` - 部分bash命令在Docker容器中无意义
- `DL3002` - 最后一个USER不应为root
- `DL3003` - 使用WORKDIR切换目录
- `DL3004` - 不要使用sudo
- `DL3006` - 始终为镜像版本打标签(避免使用:latest)
- `DL3007` - 不推荐使用latest标签
- `DL3008` - 在apt-get install中固定版本
- `DL3009` - 安装后删除apt缓存
- `DL3013` - 在pip install中固定版本
- `DL3014` - 为apt-get使用-y参数
- `DL3015` - 避免通过apt-get安装额外包
- `DL3016` - 在npm install中固定版本
- `DL3018` - 在apk add中固定版本
- `DL3019` - 为apk add使用--no-cache参数
- `DL3020` - 复制文件时使用COPY而非ADD
- `DL3021` - 从之前阶段复制时应按名称引用
- `DL3022` - COPY --from应引用之前定义的FROM别名
- `DL3025` - 对CMD和ENTRYPOINT使用JSON格式
- `DL3059` - 多个连续的RUN指令(应合并以优化分层)
**SC前缀规则(针对RUN命令的ShellCheck规则):**
- `SC1091` - 未跟踪被引用的文件
- `SC2046` - 添加引号以防止分词
- `SC2086` - 使用双引号以防止通配
- `SC2164` - 使用cd ... || exit进行错误处理
**规则严重级别:**
- **error** - 可能导致构建失败或运行时问题
- **warning** - 违反最佳实践,应修复
- **info** - 改进建议
- **style** - 代码风格偏好
**最佳实践:**
- 每次docker build前运行hadolint
- 集成到CI/CD流水线中
- 为项目配置.hadolint.yaml自定义规则
- 先处理错误再处理警告
- 谨慎使用内联忽略注释并附上理由2. Security Scanning with Checkov
2. 基于Checkov的安全扫描
Purpose: Detect security misconfigurations and vulnerabilities before image deployment.
Tool: Checkov - Policy-as-code security scanner with 50+ built-in Dockerfile policies.
Installation:
The validation script automatically installs Checkov in an isolated Python venv if not found. For permanent installation:
bash
undefined目标: 在镜像部署前检测安全配置错误和漏洞。
工具: Checkov - 基于策略即代码的安全扫描工具,内置50+ Dockerfile策略。
安装方式:
若未找到工具,验证脚本会自动在隔离的Python虚拟环境中安装。如需永久安装:
bash
undefinedInstall directly
直接安装
pip3 install checkov
pip3 install checkov
macOS Homebrew
macOS Homebrew
brew install checkov
brew install checkov
Verify installation
验证安装
checkov --version
**Workflow:**
```bashcheckov --version
**使用流程:**
```bashScan a Dockerfile
扫描单个Dockerfile
checkov -f Dockerfile --framework dockerfile
checkov -f Dockerfile --framework dockerfile
Scan a directory (finds all Dockerfiles)
扫描目录(自动查找所有Dockerfile)
checkov -d . --framework dockerfile
checkov -d . --framework dockerfile
Scan with compact output (only failures)
简洁输出(仅显示失败项)
checkov -f Dockerfile --framework dockerfile --compact
checkov -f Dockerfile --framework dockerfile --compact
Scan with JSON output
以JSON格式输出
checkov -f Dockerfile --framework dockerfile -o json
checkov -f Dockerfile --framework dockerfile -o json
Skip specific checks
跳过特定检查
checkov -f Dockerfile --framework dockerfile --skip-check CKV_DOCKER_2
**Common Security Checks:**
**General Security:**
- `CKV_DOCKER_1` - Ensure port 22 (SSH) is not exposed
- `CKV_DOCKER_2` - Ensure HEALTHCHECK instruction exists
- `CKV_DOCKER_3` - Ensure user is created and used (not root)
- `CKV_DOCKER_4` - Ensure ADD is not used (prefer COPY)
- `CKV_DOCKER_5` - Ensure update without install is not used alone
- `CKV_DOCKER_6` - Ensure SHELL instruction uses -o pipefail
- `CKV_DOCKER_7` - Ensure base image uses specific version tag
- `CKV_DOCKER_8` - Ensure last USER is not root
- `CKV_DOCKER_9` - Ensure apt-get dist-upgrade is not used
- `CKV_DOCKER_10` - Ensure yum update is not used alone
**Package Management:**
- Check for missing package manager cache cleanup
- Verify version pinning for installed packages
- Detect use of --no-install-recommends for apt-get
**Secrets Detection:**
- Scan for potential secrets in ENV or ARG
- Detect hardcoded credentials
- Identify exposed API keys or tokens
**Output Formats:**
- `cli` - Human-readable console output (default)
- `json` - JSON format for programmatic parsing
- `sarif` - SARIF format for IDE integration
- `gitlab_sast` - GitLab security dashboard format
- `junitxml` - JUnit XML for CI integration
**Understanding Results:**
Check: "Ensure that HEALTHCHECK instructions have been added to container images"
FAILED for resource: Dockerfile.
File: /Dockerfile:1-20
Guide: https://docs.bridgecrew.io/docs/ensure-that-healthcheck-instructions-have-been-added-to-container-images
1 | FROM node:18
20 | CMD ["node", "server.js"]
**Suppressing False Positives:**
Add inline comments to suppress specific checks:
```dockerfilecheckov -f Dockerfile --framework dockerfile --skip-check CKV_DOCKER_2
**常见安全检查项:**
**通用安全:**
- `CKV_DOCKER_1` - 确保未暴露22端口(SSH)
- `CKV_DOCKER_2` - 确保存在HEALTHCHECK指令
- `CKV_DOCKER_3` - 确保创建并使用非root用户
- `CKV_DOCKER_4` - 确保未使用ADD(优先使用COPY)
- `CKV_DOCKER_5` - 确保未单独使用无安装操作的update命令
- `CKV_DOCKER_6` - 确保SHELL指令使用-o pipefail
- `CKV_DOCKER_7` - 确保基础镜像使用特定版本标签
- `CKV_DOCKER_8` - 确保最后一个USER不是root
- `CKV_DOCKER_9` - 确保未使用apt-get dist-upgrade
- `CKV_DOCKER_10` - 确保未单独使用yum update
**包管理:**
- 检查是否缺少包管理器缓存清理
- 验证已安装包的版本固定
- 检测apt-get是否使用--no-install-recommends
**密钥检测:**
- 扫描ENV或ARG中的潜在密钥
- 检测硬编码凭证
- 识别暴露的API密钥或令牌
**输出格式:**
- `cli` - 人类可读的控制台输出(默认)
- `json` - 用于程序解析的JSON格式
- `sarif` - 用于IDE集成的SARIF格式
- `gitlab_sast` - GitLab安全仪表板格式
- `junitxml` - 用于CI集成的JUnit XML格式
**结果解读:**
检查项: "确保容器镜像中已添加HEALTHCHECK指令"
针对资源Dockerfile验证失败。
文件: /Dockerfile:1-20
指南: https://docs.bridgecrew.io/docs/ensure-that-healthcheck-instructions-have-been-added-to-container-images
1 | FROM node:18
20 | CMD ["node", "server.js"]
**抑制误报:**
添加内联注释以跳过特定检查:
```dockerfilecheckov:skip=CKV_DOCKER_2:Health check not applicable for this init container
checkov:skip=CKV_DOCKER_2:该初始化容器无需健康检查
FROM alpine:3.21
...
**Exit Codes:**
- `0` - All checks passed
- `1` - One or more checks failed
**Best Practices:**
- Run Checkov after hadolint (syntax first, then security)
- Address high-severity findings first
- Document all suppressions with clear justification
- Integrate into CI/CD pipelines
- Review new policies regularly
- Combine with image vulnerability scanning (e.g., trivy, snyk)FROM alpine:3.21
...
**退出码:**
- `0` - 所有检查通过
- `1` - 一项或多项检查失败
**最佳实践:**
- 在hadolint之后运行Checkov(先检查语法,再检查安全)
- 优先处理高严重级别的问题
- 为所有抑制操作添加清晰的理由说明
- 集成到CI/CD流水线中
- 定期查看新策略
- 结合镜像漏洞扫描工具(如trivy、snyk)使用3. Best Practices Validation
3. 最佳实践验证
Purpose: Ensure Dockerfiles follow official Docker best practices and current recommendations.
Custom Validation Checks:
1. Base Image Validation:
bash
undefined目标: 确保Dockerfile遵循官方Docker最佳实践和当前推荐规范。
自定义验证检查:
1. 基础镜像验证:
bash
undefinedCheck for :latest tag usage
检查是否使用:latest标签
grep -E "^FROM.*:latest" Dockerfile
grep -E "^FROM.*:latest" Dockerfile
Recommend specific tags or digest pinning
推荐使用特定标签或摘要固定
Good: FROM alpine:3.21
推荐写法: FROM alpine:3.21
Better: FROM alpine:3.21@sha256:digest
更优写法: FROM alpine:3.21@sha256:digest
**2. Multi-Stage Build Detection:**
```bash
**2. 多阶段构建检测:**
```bashCount FROM statements
统计FROM语句数量
grep -c "^FROM" Dockerfile
grep -c "^FROM" Dockerfile
Single FROM suggests potential for multi-stage optimization
单个FROM语句意味着有机会通过多阶段构建优化
**3. USER Directive Check:**
```bash
**3. USER指令检查:**
```bashEnsure USER is set before CMD/ENTRYPOINT
确保在CMD/ENTRYPOINT之前设置USER
Check that last USER is not root
检查最后一个USER不是root
grep "^USER" Dockerfile
**4. HEALTHCHECK Presence:**
```bashgrep "^USER" Dockerfile
**4. HEALTHCHECK存在性检查:**
```bashVerify HEALTHCHECK is defined for services
验证服务是否定义了HEALTHCHECK
grep "^HEALTHCHECK" Dockerfile
**5. Layer Efficiency:**
```bashgrep "^HEALTHCHECK" Dockerfile
**5. 分层效率:**
```bashCount RUN commands (>5 suggests combination opportunity)
统计RUN命令数量(超过5个意味着有合并机会)
grep -c "^RUN" Dockerfile
grep -c "^RUN" Dockerfile
Check for apt-get update separated from install
检查apt-get update是否与install分开
grep -A1 "^RUN.*apt-get update" Dockerfile
**6. Package Manager Cache Cleanup:**
```bashgrep -A1 "^RUN.*apt-get update" Dockerfile
**6. 包管理器缓存清理:**
```bashVerify cache cleanup in same RUN layer
验证是否在同一个RUN分层中清理缓存
grep "rm -rf /var/lib/apt/lists" Dockerfile
grep "--no-cache" Dockerfile # for apk
**Best Practices Checklist:**
**Base Images:**
- ✓ Use specific version tags, not :latest
- ✓ Consider Alpine variants for smaller size
- ✓ Pin to digest for reproducibility
- ✓ Use official images from verified publishers
- ✓ Scan base images for vulnerabilities
**Layer Optimization:**
- ✓ Combine related RUN commands with &&
- ✓ Order instructions from least to most frequently changing
- ✓ COPY package files before source code
- ✓ Clean up package manager caches in same layer
- ✓ Use .dockerignore to exclude unnecessary files
**Security:**
- ✓ Run as non-root user (USER directive)
- ✓ Don't install unnecessary packages (--no-install-recommends)
- ✓ Don't hardcode secrets (use build secrets or runtime configs)
- ✓ Use COPY instead of ADD (unless extracting archives)
- ✓ Avoid curl | bash installations
**Multi-Stage Builds:**
- ✓ Separate build dependencies from runtime
- ✓ Name stages explicitly (FROM ... AS stagename)
- ✓ Copy only necessary artifacts between stages
- ✓ Use minimal runtime base images
**Runtime Configuration:**
- ✓ Define HEALTHCHECK for services
- ✓ Use exec form for ENTRYPOINT and CMD
- ✓ Set WORKDIR to absolute paths
- ✓ Document exposed ports with EXPOSE
- ✓ Add metadata with LABEL
**Build Performance:**
- ✓ Leverage build cache by proper instruction ordering
- ✓ Use BuildKit features (--mount=type=cache)
- ✓ Minimize context size with .dockerignore
- ✓ Parallelize multi-stage builds when possiblegrep "rm -rf /var/lib/apt/lists" Dockerfile
grep "--no-cache" Dockerfile # 针对apk
**最佳实践清单:**
**基础镜像:**
- ✓ 使用特定版本标签,而非:latest
- ✓ 考虑使用Alpine变体以减小镜像大小
- ✓ 使用摘要固定以确保可复现性
- ✓ 使用官方认证发布者的镜像
- ✓ 扫描基础镜像的漏洞
**分层优化:**
- ✓ 使用&&合并相关RUN命令
- ✓ 按变更频率从低到高排序指令
- ✓ 先复制包文件再复制源代码
- ✓ 在同一个RUN分层中清理包管理器缓存
- ✓ 使用.dockerignore排除不必要的文件
**安全:**
- ✓ 以非root用户运行(USER指令)
- ✓ 不安装不必要的包(使用--no-install-recommends)
- ✓ 不硬编码密钥(使用构建密钥或运行时配置)
- ✓ 复制文件时使用COPY而非ADD(除非需要解压归档)
- ✓ 避免使用curl | bash方式安装
**多阶段构建:**
- ✓ 将构建依赖与运行时环境分离
- ✓ 显式命名构建阶段(FROM ... AS stagename)
- ✓ 在阶段之间仅复制必要的产物
- ✓ 使用轻量级运行时基础镜像
**运行时配置:**
- ✓ 为服务定义HEALTHCHECK
- ✓ 对ENTRYPOINT和CMD使用exec格式
- ✓ 将WORKDIR设置为绝对路径
- ✓ 使用EXPOSE声明暴露的端口
- ✓ 使用LABEL添加元数据
**构建性能:**
- ✓ 通过合理的指令顺序利用构建缓存
- ✓ 使用BuildKit特性(--mount=type=cache)
- ✓ 使用.dockerignore减小构建上下文大小
- ✓ 尽可能并行化多阶段构建4. Optimization Analysis
4. 优化分析
Purpose: Identify opportunities to reduce image size, build time, and layer count.
Optimization Categories:
1. Image Size Reduction:
dockerfile
undefined目标: 识别减小镜像大小、缩短构建时间和减少分层数量的机会。
优化类别:
1. 镜像大小缩减:
dockerfile
undefinedBad: Full distro
不佳写法:完整发行版
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y curl
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y curl
Good: Minimal distro
推荐写法:轻量级发行版
FROM alpine:3.21
RUN apk add --no-cache curl
FROM alpine:3.21
RUN apk add --no-cache curl
Better: Multi-stage with distroless
更优写法:多阶段构建+无发行版镜像
FROM golang:1.21 AS build
WORKDIR /app
COPY . .
RUN go build -o myapp
FROM gcr.io/distroless/base-debian11
COPY --from=build /app/myapp /
ENTRYPOINT ["/myapp"]
**2. Layer Optimization:**
```dockerfileFROM golang:1.21 AS build
WORKDIR /app
COPY . .
RUN go build -o myapp
FROM gcr.io/distroless/base-debian11
COPY --from=build /app/myapp /
ENTRYPOINT ["/myapp"]
**2. 分层优化:**
```dockerfileBad: Separate RUN commands (creates many layers)
不佳写法:多个独立RUN命令(创建多个分层)
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y git
RUN apt-get install -y vim
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y git
RUN apt-get install -y vim
Good: Combined RUN (single layer)
推荐写法:合并RUN命令(单个分层)
RUN apt-get update && apt-get install -y --no-install-recommends
curl
git
vim
&& rm -rf /var/lib/apt/lists/*
curl
git
vim
&& rm -rf /var/lib/apt/lists/*
**3. Build Cache Efficiency:**
```dockerfileRUN apt-get update && apt-get install -y --no-install-recommends
curl
git
vim
&& rm -rf /var/lib/apt/lists/*
curl
git
vim
&& rm -rf /var/lib/apt/lists/*
**3. 构建缓存效率:**
```dockerfileBad: Copy all, then install dependencies
不佳写法:先复制所有文件再安装依赖
COPY . /app
RUN pip install -r requirements.txt
COPY . /app
RUN pip install -r requirements.txt
Good: Copy dependency file first
推荐写法:先复制依赖文件
COPY requirements.txt /app/
RUN pip install -r requirements.txt
COPY . /app
**4. Multi-Stage Build Opportunities:**
```dockerfileCOPY requirements.txt /app/
RUN pip install -r requirements.txt
COPY . /app
**4. 多阶段构建机会识别:**
```dockerfileDetects single-stage builds that could benefit from separation
检测可通过分离优化的单阶段构建
Look for:
关注以下特征:
- Build tools installed but not needed at runtime
- 安装了构建工具但运行时不需要
- Source code copied but only binary needed
- 复制了源代码但仅需要二进制文件
- Development dependencies mixed with runtime
- 开发依赖与运行时依赖混合
**Optimization Metrics:**
- **Layer count:** Fewer layers = smaller image
- **Image size:** Minimal base + cleanup = smaller download
- **Build time:** Cache hits + parallel stages = faster builds
- **Attack surface:** Fewer packages = fewer vulnerabilities
**Reference Documentation:**
Load detailed best practices:references/docker_best_practices.md - Official Docker recommendations
references/optimization_guide.md - Layer and size optimization techniques
undefined
**优化指标:**
- **分层数量:** 分层越少,镜像越小
- **镜像大小:** 轻量级基础镜像+缓存清理=更小的下载体积
- **构建时间:** 缓存命中+并行阶段=更快的构建
- **攻击面:** 包越少,漏洞越少
**参考文档:**
加载详细最佳实践:references/docker_best_practices.md - 官方Docker推荐规范
references/optimization_guide.md - 分层与大小优化技巧
undefined5. .dockerignore Validation
5. .dockerignore验证
Purpose: Ensure build context is optimized by excluding unnecessary files.
Validation Checks:
bash
undefined目标: 通过排除不必要的文件优化构建上下文。
验证检查:
bash
undefinedCheck if .dockerignore exists
检查.dockerignore是否存在
if [ ! -f .dockerignore ]; then
echo "WARNING: .dockerignore file not found"
fi
if [ ! -f .dockerignore ]; then
echo "警告:未找到.dockerignore文件"
fi
Common patterns that should be included
应包含的常见模式
.git
.gitignore
README.md
.env
.log
node_modules
.md
.dockerignore
Dockerfile
docker-compose.yml
**Benefits of .dockerignore:**
- Reduces build context size
- Faster builds (less data to transfer)
- Prevents accidental secret leaks
- Excludes development-only files
**Best Practices:**
- Always create .dockerignore for non-trivial projects
- Include .git directory
- Exclude local configuration files (.env, *.local)
- Exclude documentation unless needed in image
- Exclude test files and test data
- Pattern syntax similar to .gitignore.git
.gitignore
README.md
.env
.log
node_modules
.md
.dockerignore
Dockerfile
docker-compose.yml
**.dockerignore的优势:**
- 减小构建上下文大小
- 加快构建速度(减少传输的数据量)
- 防止意外泄露密钥
- 排除仅用于开发的文件
**最佳实践:**
- 对于非小型项目,始终创建.dockerignore
- 包含.git目录
- 排除本地配置文件(.env、*.local)
- 排除文档(除非镜像中需要)
- 排除测试文件和测试数据
- 模式语法与.gitignore类似Tool Prerequisites
工具前置要求
The validation script automatically installs tools if not found. No manual installation required.
For permanent installations:
bash
undefined验证脚本会自动安装缺失的工具,无需手动安装。
如需永久安装:
bash
undefinedInstall hadolint
安装hadolint
brew install hadolint # macOS
brew install hadolint # macOS
Install Checkov
安装Checkov
pip3 install checkov
**Minimum Versions:**
- hadolint: >= 2.12.0
- Checkov: Latest (for newest policies)
- Python: >= 3.8 (for temporary installations)
- Docker: >= 20.10 (optional, for testing builds)
**Testing Auto-Install and Cleanup:**
To test the temporary installation and cleanup functionality even when tools are already installed:
```bashpip3 install checkov
**最低版本要求:**
- hadolint: >= 2.12.0
- Checkov: 最新版本(支持最新策略)
- Python: >= 3.8(用于临时安装)
- Docker: >= 20.10(可选,用于测试构建)
**测试自动安装与清理功能:**
即使工具已安装,也可测试临时安装和清理功能:
```bashForce temporary installation for testing
强制使用临时安装进行测试
FORCE_TEMP_INSTALL=true bash scripts/dockerfile-validate.sh Dockerfile
This will:
1. Install hadolint and Checkov in temporary Python venvs
2. Run all validations using the temporary installations
3. Clean up temporary venvs on exit (success or failure)FORCE_TEMP_INSTALL=true bash scripts/dockerfile-validate.sh Dockerfile
该命令会:
1. 在临时Python虚拟环境中安装hadolint和Checkov
2. 使用临时安装的工具运行所有验证
3. 退出时清理临时虚拟环境(无论成功或失败)Handling Missing Tools
缺失工具的处理
When validation tools are not installed:
当验证工具未安装时:
Workflow for Missing Tools
缺失工具的处理流程
-
Detect Missing Tool:
- Attempt to run hadolint or Checkov
- If command fails, note which tool is missing
-
Complete Available Validations:
- Continue with custom best practices checks
- Provide partial validation results
- Clearly indicate which checks were skipped
-
Prompt User for Installation:For hadolint:
hadolint is not installed. The script will automatically install it temporarily. For permanent installation: - macOS: brew install hadolint - Linux: wget -O ~/.local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64 && chmod +x ~/.local/bin/hadolint - Docker: docker pull hadolint/hadolint hadolint provides comprehensive Dockerfile linting and best practice checking.For Checkov:Checkov is not installed. Would you like to install it? Installation options: - Recommended: pip3 install checkov - macOS: brew install checkov Checkov provides security scanning with 50+ Dockerfile policies. Install and rerun validation? (y/N) -
If User Chooses to Install:
- Provide installation command
- Wait for completion
- Verify: or
hadolint --versioncheckov --version - Rerun complete validation
-
If User Declines:
- Continue with partial results
- Document skipped checks
- Suggest installing for future validations
-
检测缺失工具:
- 尝试运行hadolint或Checkov
- 若命令失败,记录缺失的工具
-
执行可用的验证:
- 继续执行自定义最佳实践检查
- 提供部分验证结果
- 明确标注哪些检查被跳过
-
提示用户安装:针对hadolint:
未安装hadolint。脚本将自动临时安装该工具。 永久安装方式: - macOS: brew install hadolint - Linux: wget -O ~/.local/bin/hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64 && chmod +x ~/.local/bin/hadolint - Docker: docker pull hadolint/hadolint hadolint提供全面的Dockerfile代码检查和最佳实践检测。针对Checkov:未安装Checkov。是否要安装该工具? 安装选项: - 推荐:pip3 install checkov - macOS: brew install checkov Checkov提供50+ Dockerfile策略的安全扫描功能。 是否安装并重新运行验证?(y/N) -
若用户选择安装:
- 提供安装命令
- 等待安装完成
- 验证:或
hadolint --versioncheckov --version - 重新运行完整验证
-
若用户拒绝安装:
- 继续提供部分结果
- 记录被跳过的检查
- 建议用户在未来验证时安装工具
Tool Priority
工具优先级
Required (always run):
- Custom best practices validation
- File existence checks
Recommended (offer installation if missing):
- hadolint - Syntax and best practices linting
- Checkov - Security scanning
Optional:
- docker - For test builds
- trivy - For vulnerability scanning (complementary)
必须运行(始终执行):
- 自定义最佳实践验证
- 文件存在性检查
推荐(缺失时提供安装选项):
- hadolint - 语法和最佳实践检查
- Checkov - 安全扫描
可选:
- docker - 用于测试构建
- trivy - 用于漏洞扫描(补充工具)
Error Troubleshooting
错误排查
Common Issues and Solutions
常见问题与解决方案
Error: FROM instruction must be first non-comment
Solution: Move ARG that defines base image tag before FROM
ARG VERSION=18
FROM node:${VERSION}Error: Unknown instruction (typo)
Solution: Check instruction spelling (RUN, COPY, FROM, etc.)
Common typos: RUNS, COPIES, FRUMError: Chained RUN command fails
Solution: Add set -e or check individual command success
RUN apt-get update && apt-get install -y package || exit 1Error: COPY failed: file not found
Solution: Check file path is relative to build context
Verify file exists and not excluded by .dockerignoreSecurity: Hardcoded secrets detected
Solution: Use build secrets (BuildKit)错误:FROM指令必须是第一个非注释行
解决方案:将定义基础镜像标签的ARG移至FROM之前
ARG VERSION=18
FROM node:${VERSION}错误:未知指令(拼写错误)
解决方案:检查指令拼写(RUN、COPY、FROM等)
常见拼写错误:RUNS、COPIES、FRUM错误:链式RUN命令失败
解决方案:添加set -e或检查单个命令的执行结果
RUN apt-get update && apt-get install -y package || exit 1错误:COPY失败:文件未找到
解决方案:检查文件路径是否相对于构建上下文
验证文件存在且未被.dockerignore排除安全问题:检测到硬编码密钥
解决方案:使用构建密钥(BuildKit)Instead of: ENV API_KEY=secret123
替代写法:ENV API_KEY=secret123
Use: docker build --secret id=api_key,src=api_key.txt
推荐写法:docker build --secret id=api_key,src=api_key.txt
**Performance: Slow builds**Solution:
- Optimize layer caching (COPY package files first)
- Use .dockerignore to reduce context
- Enable BuildKit: export DOCKER_BUILDKIT=1
- Use multi-stage builds
undefined
**性能问题:构建缓慢**解决方案:
- 优化分层缓存(先复制包文件)
- 使用.dockerignore减小构建上下文
- 启用BuildKit: export DOCKER_BUILDKIT=1
- 使用多阶段构建
undefinedResources
资源
scripts/
scripts/
dockerfile-validate.sh
- Single self-contained validation script
- Auto-installs hadolint and Checkov if needed
- Runs all 4 validation stages (syntax, security, best practices, optimization)
- Auto-cleanup on exit
- Usage:
bash scripts/dockerfile-validate.sh [Dockerfile]
dockerfile-validate.sh
- 独立的自包含验证脚本
- 自动安装缺失的hadolint和Checkov
- 运行全部4个验证阶段(语法、安全、最佳实践、优化)
- 退出时自动清理
- 使用方式:
bash scripts/dockerfile-validate.sh [Dockerfile]
examples/
examples/
good-example.Dockerfile - Demonstrates best practices and optimal structure
bad-example.Dockerfile - Common mistakes and anti-patterns
security-issues.Dockerfile - Intentional security vulnerabilities for testing
python-optimized.Dockerfile - Python-specific optimizations and multi-stage build
golang-distroless.Dockerfile - Minimal Go application using distroless base image
.dockerignore.example - Example .dockerignore for build context optimization
good-example.Dockerfile - 展示最佳实践和最优结构
bad-example.Dockerfile - 常见错误和反模式
security-issues.Dockerfile - 用于测试的故意设置的安全漏洞
python-optimized.Dockerfile - Python专属优化和多阶段构建示例
golang-distroless.Dockerfile - 使用无发行版基础镜像的轻量级Go应用示例
.dockerignore.example - 用于优化构建上下文的.dockerignore示例
references/
references/
docker_best_practices.md - Official Docker best practices and recommendations
optimization_guide.md - Layer optimization and image size reduction techniques
security_checklist.md - Container security best practices
docker_best_practices.md - 官方Docker最佳实践和推荐规范
optimization_guide.md - 分层与大小优化技巧
security_checklist.md - 容器安全最佳实践
Mandatory Workflow Requirements
强制工作流要求
IMPORTANT: When using this skill, you MUST follow these steps in order:
重要提示: 使用该工具时,必须按以下顺序执行步骤:
Pre-Validation (Required)
验证前(必须执行)
- Read the Dockerfile first - Always use the Read tool to examine the Dockerfile before running validation. This helps you understand the context and provide better recommendations.
- 先读取Dockerfile - 始终使用读取工具在运行验证前检查Dockerfile,这有助于理解上下文并提供更优建议。
Validation (Required)
验证阶段(必须执行)
- Run the validation script - Execute to run all 4 validation stages.
bash scripts/dockerfile-validate.sh <Dockerfile>
- 运行验证脚本 - 执行运行全部4个验证阶段。
bash scripts/dockerfile-validate.sh <Dockerfile>
Post-Validation (Required)
验证后(必须执行)
-
Summarize findings by severity - After validation completes, provide a clear summary organized by:
- Critical issues (security vulnerabilities, hardcoded secrets)
- High priority (missing USER, HEALTHCHECK, :latest tags)
- Medium priority (layer optimization, version pinning)
- Low priority (style, informational)
-
Propose specific fixes - For each issue found, provide concrete code examples showing how to fix it. You MUST use the Read tool to load the appropriate reference files before proposing fixes:
- - For security-related fixes
references/security_checklist.md - - For performance/size improvements
references/optimization_guide.md - - For general best practices
references/docker_best_practices.md
Note: Always explicitly read reference files during the post-validation phase to ensure fix recommendations follow authoritative patterns, even if you have prior knowledge of the content. -
Offer to apply fixes - Ask the user if they want you to apply the proposed fixes to their Dockerfile.
-
按严重程度总结结果 - 验证完成后,按以下分类提供清晰的总结:
- 关键问题(安全漏洞、硬编码密钥)
- 高优先级(缺失USER、HEALTHCHECK、:latest标签)
- 中优先级(分层优化、版本固定)
- 低优先级(风格、信息提示)
-
提出具体修复方案 - 针对每个发现的问题,提供具体的代码示例展示修复方法。必须使用读取工具在提出修复前加载相应的参考文件:
- - 针对安全相关修复
references/security_checklist.md - - 针对性能/大小优化
references/optimization_guide.md - - 针对通用最佳实践
references/docker_best_practices.md
注意: 即使你已了解内容,在验证后阶段也必须显式读取参考文件,以确保修复建议遵循权威规范。 -
提供修复应用选项 - 询问用户是否需要将提出的修复应用到他们的Dockerfile中。
Reference File Usage
参考文件使用规范
IMPORTANT: After running validation, you MUST use the Read tool to explicitly load the appropriate reference files before proposing fixes. This ensures fix recommendations are accurate and follow authoritative patterns.
Workflow:
- Identify issue types from validation output (security, optimization, best practices)
- Use the Read tool to load the matching reference file(s)
- Apply patterns from the reference files when proposing fixes
| Issue Type | Reference File | Action |
|---|---|---|
| Security issues (secrets, USER, ports) | | Read before proposing security fixes |
| Size/performance optimization | | Read before proposing optimization fixes |
| General best practices | | Read before proposing best practice fixes |
Example:
undefined重要提示: 运行验证后,在提出修复前必须使用读取工具显式加载相应的参考文件,确保修复建议准确且遵循权威规范。
工作流:
- 从验证输出中识别问题类型(安全、优化、最佳实践)
- 使用读取工具加载匹配的参考文件
- 提出修复时应用参考文件中的规范
| 问题类型 | 参考文件 | 操作 |
|---|---|---|
| 安全问题(密钥、USER、端口) | | 提出安全修复前读取 |
| 大小/性能优化 | | 提出优化修复前读取 |
| 通用最佳实践 | | 提出最佳实践修复前读取 |
示例:
undefinedAfter validation finds security issues:
验证发现安全问题后:
- Use Read tool: Read references/security_checklist.md
- Apply fix patterns from the file to the specific issues found
- Propose fixes with code examples based on reference content
undefined- 使用读取工具:读取references/security_checklist.md
- 将文件中的修复规范应用到具体发现的问题
- 基于参考内容提出带代码示例的修复方案
undefinedWorkflow Examples
工作流示例
Example 1: Validate a Single Dockerfile
示例1:验证单个Dockerfile
User: "Validate my Dockerfile"
Steps:
1. Read the Dockerfile using Read tool to understand structure
2. Run validation script: bash scripts/dockerfile-validate.sh Dockerfile
3. Review output from all 4 stages (hadolint, Checkov, best practices, optimization)
4. Summarize findings organized by severity (critical → low)
5. Use Read tool to load relevant reference files:
- Read references/security_checklist.md (if security issues found)
- Read references/optimization_guide.md (if optimization issues found)
- Read references/docker_best_practices.md (if best practice issues found)
6. Propose specific fixes with code examples based on reference content
7. Ask user: "Would you like me to apply these fixes?"
8. Apply fixes if user approves用户:“验证我的Dockerfile”
步骤:
1. 使用读取工具读取Dockerfile以理解结构
2. 运行验证脚本:bash scripts/dockerfile-validate.sh Dockerfile
3. 查看全部4个阶段的输出(hadolint、Checkov、最佳实践、优化)
4. 按严重程度(关键→低优先级)组织并总结结果
5. 使用读取工具加载相关参考文件:
- 若发现安全问题,读取references/security_checklist.md
- 若发现优化机会,读取references/optimization_guide.md
- 若发现最佳实践问题,读取references/docker_best_practices.md
6. 基于参考内容提出带代码示例的具体修复方案
7. 询问用户:“是否需要我将这些修复应用到你的Dockerfile中?”
8. 若用户同意则应用修复Example 2: Comprehensive Multi-Dockerfile Validation
示例2:批量验证多个Dockerfile
User: "Check all Dockerfiles in my project"
Steps:
1. Find all Dockerfile* files
2. Validate each sequentially
3. Aggregate results
4. Identify common issues across files
5. Provide unified report
6. Suggest project-wide improvements用户:“检查我项目中的所有Dockerfile”
步骤:
1. 查找所有Dockerfile*文件
2. 依次验证每个文件
3. 汇总结果
4. 识别所有文件中的共性问题
5. 提供统一的报告
6. 提出项目级别的改进建议Example 3: Security Audit
示例3:安全审计
User: "Security audit my Dockerfile"
Steps:
1. Run Checkov security scan
2. Run hadolint for security rules (DL3* series)
3. Check for hardcoded secrets
4. Verify USER directive
5. Check base image vulnerabilities
6. Provide security-focused report
7. Prioritize critical findings用户:“对我的Dockerfile进行安全审计”
步骤:
1. 运行Checkov安全扫描
2. 运行hadolint的安全规则(DL3*系列)
3. 检查硬编码密钥
4. 验证USER指令
5. 检查基础镜像漏洞
6. 提供聚焦安全的报告
7. 优先处理关键发现Example 4: Optimization Review
示例4:优化评审
User: "How can I optimize my Dockerfile?"
Steps:
1. Analyze current layer structure
2. Identify multi-stage opportunities
3. Check build cache efficiency
4. Suggest base image alternatives
5. Calculate potential size savings
6. Provide before/after comparison
7. Implement optimizations if approved用户:“如何优化我的Dockerfile?”
步骤:
1. 分析当前分层结构
2. 识别多阶段构建机会
3. 检查构建缓存效率
4. 推荐替代基础镜像
5. 计算潜在的大小缩减量
6. 提供优化前后的对比
7. 若用户同意则实施优化Integration with Other Skills
与其他工具的集成
This skill works well in combination with:
- dockerfile-generator - Generate optimized Dockerfiles
- k8s-yaml-validator - Validate Kubernetes deployments that reference Docker images
- helm-validator - Validate Helm charts with container configurations
该工具可与以下工具配合使用:
- dockerfile-generator - 生成优化的Dockerfile
- k8s-yaml-validator - 验证引用Docker镜像的Kubernetes部署文件
- helm-validator - 验证包含容器配置的Helm Chart
Notes
注意事项
- Always validate before building images
- Address security issues before optimizations
- Test builds after applying fixes
- Version pin base images for reproducibility
- Use multi-stage builds for compiled languages
- Keep production images minimal (distroless, Alpine)
- Never commit Dockerfiles with hardcoded secrets
- Document inline suppressions with clear justification
- Regularly update base images for security patches
- Integrate validation into CI/CD pipelines
- 构建镜像前始终先执行验证
- 先处理安全问题再进行优化
- 应用修复后测试构建
- 固定基础镜像版本以确保可复现性
- 编译型语言使用多阶段构建
- 生产镜像保持最小化(使用无发行版、Alpine镜像)
- 绝不提交包含硬编码密钥的Dockerfile
- 为内联抑制操作添加清晰的理由说明
- 定期更新基础镜像以获取安全补丁
- 将验证集成到CI/CD流水线中
Sources
资料来源
This skill is based on comprehensive research from authoritative sources:
Official Docker Documentation:
Security Guidelines:
Best Practices Resources:
该工具基于以下权威来源的综合研究:
官方Docker文档:
安全指南:
最佳实践资源: