关于 Docker Configuration Validator
Docker Configuration Validator 是用于审查 Dockerfile 和 Docker Compose 配置的技能,面向开发和运维人员。它结合静态检查工具与手动清单,覆盖语法、最佳实践、安全和生产就绪性。
主要功能
- 01检查 Dockerfile 与 Compose 文件
- 02审查安全配置与最佳实践
- 03验证多阶段构建
- 04按严重性分类问题
- 05生成验证报告与自动化方案
适用场景
- 01提交前审查容器配置
- 02排查 Docker 安全隐患
- 03检查 Compose 现代语法
- 04准备 CI/CD 验证脚本
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ rknall/ claude-skills --skill docker-configuration-validator安装后在 Claude Code 中输入/docker-configuration-validator确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.mdtool-installation.mdvalidation-checklist.md详细介绍
Docker 配置验证器
此技能可全面验证 Dockerfile 和 Docker Compose 文件,确保它们符合最佳实践、安全标准和现代语法要求。
何时使用此技能
当用户请求以下操作时,启用此技能:
- 验证 Dockerfile 或 Docker Compose 文件
- 根据最佳实践审查 Docker 配置
- 检查 Docker 安全问题
- 验证多阶段构建的实现
- 审计 Docker 设置,确保其可用于生产环境
- 确保符合现代 Docker Compose 语法
- 修复 Docker 配置问题
- 创建验证脚本或集成 CI/CD
核心工作流
阶段 1:初步评估
用户请求验证 Docker 配置时,先了解验证范围:
-
确定验证对象
- 单个 Dockerfile 还是多个?
- Docker Compose 文件?
- 整个项目目录?
- 是否有具体的关注点或重点?
- 生产环境还是开发环境?
-
了解需求
- 所需的安全合规级别?
- 是否需要多阶段构建?
- 性能限制?
- 是否需要集成 CI/CD?
- 是否需要自动化验证脚本?
-
检查可用工具
- 是否已安装 Hadolint?(Dockerfile 检查工具)
- 是否已安装 DCLint?(Docker Compose 检查工具)
- 是否已安装 Docker CLI?
- 是否需要在流程中安装这些工具?
阶段 2:Dockerfile 验证
步骤 1:查找 Dockerfile
查找项目中的所有 Dockerfile:
find . -type f \( -name "Dockerfile*" ! -name "*.md" \)
步骤 2:运行 Hadolint 验证
如果 Hadolint 可用:
# Validate each Dockerfile
hadolint Dockerfile
# JSON output for programmatic analysis
hadolint --format json Dockerfile
# Set failure threshold
hadolint --failure-threshold error Dockerfile
如果 Hadolint 不可用:
- 使用内置检查进行手动验证(见步骤 3)
- 建议安装 Hadolint
- 提供安装说明
步骤 3:手动验证 Dockerfile
检查每个 Dockerfile 是否存在严重问题:
1. 基础镜像最佳实践
- ✅ 检查:不使用
:latest标签 - ✅ 检查:固定具体版本
- ✅ 检查:使用精简基础镜像(alpine/slim 变体)
- ✅ 检查:使用可信镜像仓库
2. 多阶段构建验证
# Count FROM statements (should be >= 2 for multi-stage)
FROM_COUNT=$(grep -c "^FROM " Dockerfile)
# Check for named stages
NAMED_STAGES=$(grep -c "^FROM .* AS " Dockerfile)
# Check for inter-stage copies
COPY_FROM=$(grep -c "COPY --from=" Dockerfile)
分析:
- 如果 FROM_COUNT >= 2:检测到多阶段构建 ✅
- 如果 COPY_FROM == 0 且 FROM_COUNT >= 2:警告 - 可能未传输构建产物
- 如果 FROM_COUNT == 1:单阶段构建 - 建议使用多阶段构建进行优化
3. 安全检查
- ✅ 检查:存在 USER 指令(非 root 用户)
- ✅ 检查:最后一个 USER 不是 root
- ✅ 检查:Dockerfile 中没有密钥
- ✅ 检查:WORKDIR 使用绝对路径
- ✅ 检查:没有不必要的权限
4. 层优化
- ✅ 检查:合并 RUN 命令
- ✅ 检查:清理包管理器缓存
- ✅ 检查:先 COPY 再 RUN,以改善缓存效果
- ✅ 检查:存在 .dockerignore 文件
5. 最佳实践
- ✅ 检查:定义了 HEALTHCHECK
- ✅ 检查:使用 WORKDIR(而非 cd)
- ✅ 检查:优先使用 COPY 而非 ADD
- ✅ 检查:CMD/ENTRYPOINT 使用 JSON 表示法
- ✅ 检查:包含标签(维护者、版本)
步骤 4:Dockerfile 问题分类
按严重程度对发现的问题进行分类:
严重(必须修复):
- 以 root 用户运行
- 使用
:latest标签 - 镜像中暴露密钥
- 语法无效
高(应该修复):
- 在适用时未使用多阶段构建
- 没有 HEALTHCHECK
- 未固定软件包版本
- 安全漏洞
中(建议修复):
- 使用 ADD 而非 COPY
- 未清理包缓存
- 缺少标签
- 层结构效率低下
低(有则更好):
- 可以使用更精简的基础镜像
- 可以合并更多 RUN 命令
- 可以改进注释
阶段 3:Docker Compose 验证
步骤 1:查找 Compose 文件
查找所有 Docker Compose 文件:
find . -maxdepth 3 -type f \( -name "docker-compose*.yml" -o -name "docker-compose*.yaml" -o -name "compose*.yml" \)
步骤 2:检查是否存在已废弃的 version 字段
**严重检查:**现代 Docker Compose(v2.27.0+)不使用 version 字段
# Check for obsolete version field
if grep -q "^version:" docker-compose.yml; then
echo "❌ ERROR: Found obsolete 'version' field"
echo "Remove 'version:' line - it's obsolete in Compose v2.27.0+"
fi
旧版(已弃用):
version: '3.8' # ❌ REMOVE THIS
services:
web:
image: nginx:latest
新版(现代):
# No version field!
services:
web:
image: nginx:1.24-alpine
步骤 3:使用 Docker Compose 内置验证
# Syntax validation
docker compose config --quiet
# Show resolved configuration
docker compose config
# Validate specific file
docker compose -f docker-compose.prod.yml config --quiet
步骤 4:使用 DCLint 验证(如果可用)
# Lint compose file
dclint docker-compose.yml
# Auto-fix issues
dclint --fix docker-compose.yml
# JSON output
dclint --format json docker-compose.yml
第 5 步:手动验证 Compose
1. 镜像最佳实践
- ✅ 检查:不使用
:latest标签 - ✅ 检查:指定具体版本
- ✅ 检查:镜像来自可信来源
2. 服务配置
- ✅ 检查:定义重启策略
- ✅ 检查:配置健康检查
- ✅ 检查:设置资源限制(可选,但建议设置)
- ✅ 检查:正确配置服务依赖关系(depends_on)
3. 网络
- ✅ 检查:定义自定义网络
- ✅ 检查:实现网络隔离
- ✅ 检查:使用适当的网络驱动程序
4. 卷与持久化
- ✅ 检查:使用命名卷实现持久化
- ✅ 检查:指定卷驱动程序
- ✅ 检查:绑定挂载使用绝对路径
- ✅ 检查:卷中不包含敏感数据
5. 环境与密钥
- ✅ 检查:妥善管理环境变量
- ✅ 检查:不硬编码密钥
- ✅ 检查:建议使用 .env 文件
- ✅ 检查:配置密钥管理
6. 安全
- ✅ 检查:不使用特权模式(除非必要)
- ✅ 检查:妥善配置功能
- ✅ 检查:指定用户/组
- ✅ 检查:只读根文件系统(适用时)
第 4 阶段:深入了解多阶段构建
验证多阶段构建时,请确保:
1. 阶段结构
# Build stage
FROM node:20-bullseye AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm run test
# Production stage
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]
2. 验证清单
- ✅ 至少包含 2 个阶段(构建 + 运行时)
- ✅ 所有阶段都使用 AS 关键字命名
- ✅ 使用 COPY --from 在阶段之间复制构建产物
- ✅ 最终阶段使用精简的基础镜像
- ✅ 最终阶段中不包含构建工具
- ✅ 最终镜像中仅包含必要文件
- ✅ 最终阶段以非 root 用户运行
3. 常见模式检查
Node.js 多阶段构建:
- 构建阶段:安装所有依赖、构建、测试
- 运行时阶段:仅包含生产依赖和构建产物
Python 多阶段构建:
- 构建阶段:编译依赖、构建 wheel 包
- 运行时阶段:安装预构建的 wheel 包,仅包含应用
Go 多阶段构建:
- 构建阶段:使用完整的 Go 工具链编译二进制文件
- 运行时阶段:使用 scratch/distroless,仅包含二进制文件
第 5 阶段:安全审计
执行全面的安全检查:
1. 用户与权限
# Check for USER directive
USER_COUNT=$(grep -c "^USER " Dockerfile)
LAST_USER=$(grep "^USER " Dockerfile | tail -1 | awk '{print $2}')
if [ "$USER_COUNT" -eq 0 ]; then
echo "❌ CRITICAL: No USER specified (runs as root!)"
elif [ "$LAST_USER" == "root" ] || [ "$LAST_USER" == "0" ]; then
echo "❌ CRITICAL: Final USER is root"
fi
2. 暴露的密钥
- 检查 ENV 中是否包含密码
- 检查 COPY/ADD 中是否包含 API 密钥
- 检查 RUN 命令中是否包含凭据
- 推荐密钥管理解决方案
3. 存在漏洞的基础镜像
- 检查基础镜像的使用年限和支持状态
- 建议进行安全扫描(Trivy、Snyk)
- 建议使用固定且受支持的版本
4. 网络暴露
- 检查 EXPOSE 指令
- 检查是否暴露了不必要的端口
- 验证 Compose 中的端口映射
第 6 阶段:生成验证报告
验证报告结构:
# Docker Configuration Validation Report
## Executive Summary
- **Total Dockerfiles Analyzed**: X
- **Total Compose Files Analyzed**: X
- **Critical Issues**: X
- **High Priority Issues**: X
- **Medium Priority Issues**: X
- **Low Priority Issues**: X
- **Overall Status**: ✅ PASS / ⚠️ WARNINGS / ❌ FAIL
## Dockerfile Analysis
### [Dockerfile Path]
#### Validation Results
✅ **PASSED**: Multi-stage build implemented
✅ **PASSED**: Running as non-root user
⚠️ **WARNING**: Using ADD instead of COPY (line 15)
❌ **FAILED**: Base image uses :latest tag (line 1)
#### Security Assessment
- **User**: nodejs (non-root) ✅
- **Base Image**: node:latest ❌
- **Secrets**: None detected ✅
- **Health Check**: Present ✅
#### Multi-Stage Build Analysis
- **Stages**: 2 (builder, runtime)
- **Named Stages**: Yes ✅
- **Inter-Stage Copies**: 1 ✅
- **Final Base**: node:20-alpine ✅
- **Build Tools in Final**: No ✅
#### Issues Found
**CRITICAL:**
1. Line 1: Using :latest tag
- Issue: `FROM node:latest`
- Fix: `FROM node:20-bullseye`
- Impact: Unpredictable builds, security risk
**HIGH:**
2. Line 45: Package cache not cleaned
- Issue: `RUN apt-get install -y curl`
- Fix: Add `&& rm -rf /var/lib/apt/lists/*`
- Impact: Larger image size
**MEDIUM:**
3. Line 15: Using ADD instead of COPY
- Issue: `ADD app.tar.gz /app/`
- Fix: `COPY app.tar.gz /app/` (or extract separately)
- Impact: Less explicit behavior
## Docker Compose Analysis
### [Compose File Path]
#### Validation Results
❌ **FAILED**: Obsolete 'version' field present
⚠️ **WARNING**: 3 services using :latest tags
✅ **PASSED**: Custom networks defined
✅ **PASSED**: Named volumes configured
#### Modern Syntax Compliance
- **Version Field**: Present ❌ (MUST REMOVE)
- **Specific Tags**: 2 of 5 services ⚠️
- **Restart Policies**: All services ✅
- **Health Checks**: 3 of 5 services ⚠️
#### Issues Found
**CRITICAL:**
1. Obsolete 'version' field
- Issue: `version: '3.8'`
- Fix: Remove the entire line
- Impact: Using deprecated syntax
**HIGH:**
2. Service 'web' uses :latest tag
- Issue: `image: nginx:latest`
- Fix: `image: nginx:1.24-alpine`
- Impact: Unpredictable deployments
3. No restart policy on 'cache' service
- Issue: Missing `restart:` directive
- Fix: Add `restart: unless-stopped`
- Impact: Service won't auto-recover
## Recommendations
### Immediate Actions (Critical)
1. Pin all Docker image versions (remove :latest)
2. Remove obsolete 'version' field from Compose files
3. Ensure all services run as non-root users
4. Clean package manager caches in all Dockerfiles
### High Priority (Before Production)
1. Implement health checks for all services
2. Add restart policies to all Compose services
3. Set up resource limits (memory, CPU)
4. Implement proper secrets management
### Medium Priority (Best Practices)
1. Use COPY instead of ADD unless extracting archives
2. Add labels for better organization
3. Implement logging drivers
4. Add metadata to images
### Low Priority (Optimizations)
1. Consider slimmer base images where possible
2. Optimize layer caching with better ordering
3. Add comprehensive comments
4. Implement .dockerignore files
## Next Steps
1. **Fix Critical Issues** (Estimated: 30 minutes)
- Pin image versions
- Remove version field from Compose
- Add USER directives
2. **Address High Priority** (Estimated: 1-2 hours)
- Add health checks
- Configure restart policies
- Set resource limits
3. **Re-validate** (Estimated: 10 minutes)
- Run validation again after fixes
- Ensure all critical issues resolved
4. **Set Up Automation** (Estimated: 1 hour)
- Add pre-commit hooks
- Integrate into CI/CD
- Schedule regular security scans
## Validation Tools Recommendations
### Install Required Tools
```bash
# Hadolint (Dockerfile linter)
brew install hadolint # macOS
# or
wget -O /usr/local/bin/hadolint https://github.com/hadolint/hadolint/releases/download/v2.12.0/hadolint-Linux-x86_64
# DCLint (Docker Compose linter)
npm install -g docker-compose-linter
# Trivy (Security scanner)
brew install aquasecurity/trivy/trivy
自动化验证脚本
[根据项目需求提供自定义验证脚本]
CI/CD 集成
[提供 GitHub Actions / GitLab CI 配置]
## Deliverables
At the end of validation, provide:
1. **Comprehensive Validation Report**
- Executive summary with overall status
- Detailed findings per file
- Issue classification (Critical → Low)
- Specific fixes for each issue
- Recommendations prioritized
2. **Fixed Configuration Files** (if requested)
- Corrected Dockerfiles
- Updated Compose files
- .hadolint.yaml configuration
- .dclintrc.json configuration
3. **Validation Script** (if requested)
- Custom bash script for automated validation
- Checks for project-specific requirements
- Color-coded output
- Exit codes for CI/CD
4. **CI/CD Integration** (if requested)
- GitHub Actions workflow
- GitLab CI configuration
- Pre-commit hooks
- Integration with existing pipeline
5. **Documentation**
- How to run validation locally
- Tool installation instructions
- Best practices guide
- Common issues and solutions
## Validation Script Template
When user requests automated validation, create this script:
```bash
#!/bin/bash
# docker-validation.sh
set -e
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
ERRORS=0
WARNINGS=0
echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ Docker Configuration Validator ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
# 1. Prerequisites check
echo -e "\n${BLUE}━━━ Checking Prerequisites ━━━${NC}"
command -v docker >/dev/null || { echo "❌ Docker not found"; exit 1; }
command -v hadolint >/dev/null || echo "⚠️ Hadolint not installed"
# 2. Dockerfile validation
echo -e "\n${BLUE}━━━ Validating Dockerfiles ━━━${NC}"
find . -name "Dockerfile*" -type f | while read df; do
echo "Checking: $df"
# [Validation logic here]
done
# 3. Multi-stage build check
echo -e "\n${BLUE}━━━ Checking Multi-Stage Builds ━━━${NC}"
# [Multi-stage validation logic]
# 4. Compose validation
echo -e "\n${BLUE}━━━ Validating Docker Compose ━━━${NC}"
find . -name "*compose*.yml" | while read cf; do
# Check for obsolete version field
if grep -q "^version:" "$cf"; then
echo -e "${RED}❌ $cf: Obsolete version field${NC}"
ERRORS=$((ERRORS + 1))
fi
# Validate syntax
docker compose -f "$cf" config --quiet || ERRORS=$((ERRORS + 1))
done
# 5. Security checks
echo -e "\n${BLUE}━━━ Security Audit ━━━${NC}"
# [Security validation logic]
# Final report
echo -e "\n${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ Validation Summary ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
if [ $ERRORS -eq 0 ]; then
echo -e "${GREEN}✅ All checks passed!${NC}"
exit 0
else
echo -e "${RED}❌ Found $ERRORS error(s), $WARNINGS warning(s)${NC}"
exit 1
fi
CI/CD 集成模板
GitHub Actions
name: Docker Validation
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Dockerfiles
uses: hadolint/[email protected]
with:
dockerfile: ./Dockerfile
failure-threshold: error
- name: Validate Compose files
run: |
for f in $(find . -name "*compose*.yml"); do
docker compose -f "$f" config --quiet
done
- name: Check for obsolete version field
run: |
if grep -r "^version:" . --include="*compose*.yml"; then
echo "ERROR: Found obsolete version field"
exit 1
fi
GitLab CI
stages:
- validate
docker-validation:
stage: validate
image: hadolint/hadolint:latest-debian
script:
- find . -name "Dockerfile*" -exec hadolint {} \;
- |
for f in $(find . -name "*compose*.yml"); do
if grep -q "^version:" "$f"; then
echo "ERROR: Obsolete version field in $f"
exit 1
fi
done
沟通风格
进行验证时:
-
全面细致
- 系统地检查各个方面
- 如果无法使用工具,也不要跳过手动检查
- 验证语法和最佳实践
-
清晰地确定优先级
- 优先处理关键问题(安全、功能)
- 接着处理高优先级问题(生产就绪性)
- 将中低优先级问题作为改进项
-
提供具体的修复方案
- 标明确切的行号
- 提供修改前后的代码
- 说明修复的必要性
- 评估影响
-
帮助用户理解
- 说明 Docker 最佳实践
- 引用官方文档
- 提供学习资源
- 分享现代语法要求
-
提供可执行的建议
- 给出分步修复方案
- 提供自动化脚本
- 建议 CI/CD 集成
- 估算修复所需工作量
常见验证模式
模式 1:快速语法检查
- 运行 Hadolint 和 DCLint
- 检查是否存在已废弃的版本字段
- 使用 Docker Compose config 验证
- 仅报告关键语法错误
模式 2:全面生产审计
- 完整验证 Dockerfile
- 验证多阶段构建
- 安全审计
- Compose 最佳实践
- 生成全面的报告
- 提供自动化脚本
模式 3:以安全为重点的审查
- 检查用户权限
- 扫描是否暴露机密信息
- 基础镜像安全性
- 网络暴露审计
- 集成安全扫描
模式 4:优化审查
- 多阶段构建效果
- 层优化
- 镜像大小分析
- 改进构建时间
- 缓存策略
必须遵守的关键规则
Dockerfile 规则(关键)
- ✅ 不使用
:latest标签(DL3006) - ✅ 最后一个 USER 不能是 root(DL3002)
- ✅ 使用绝对路径 WORKDIR(DL3000)
- ✅ 固定软件包版本(DL3008、DL3013)
- ✅ 清理软件包缓存(DL3009)
Docker Compose 规则(关键)
- ✅ 不使用 version 字段(自 v2.27.0 起已弃用)
- ✅ 不使用
:latest标签 - ✅ 定义重启策略
- ✅ 配置健康检查
- ✅ 使用命名卷实现持久化
多阶段构建规则
- ✅ 至少包含 2 个阶段
- ✅ 使用 AS 命名阶段
- ✅ 使用 COPY --from 复制构件
- ✅ 最终基础镜像尽可能精简
- ✅ 最终阶段不包含构建工具
安全规则(关键)
- ✅ 以非 root USER 运行
- ✅ 镜像中不包含机密信息
- ✅ 使用精简的基础镜像
- ✅ 定期执行安全扫描
- ✅ 遵循最小权限原则
参考资源
提供建议时,请参考:
- Docker 最佳实践:Docker 官方文档
- Hadolint 规则:完整规则参考
- Compose 规范:最新 Compose 规范
- 安全标准:CIS Docker 基准
- 多阶段构建:官方指南和示例
请记住:Docker 验证旨在确保容器化应用可靠、安全且高效。在提升开发者体验的同时,始终将安全性和生产就绪性放在首位。