dockerfile-skill
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDockerfile Generator Skill
Dockerfile生成工具
Overview
概述
This skill generates production-ready Dockerfiles through a 4-phase process:
- Deep Analysis - Understand project structure, workspace, migrations, and build complexity
- Generate - Create Dockerfile with migration handling and build optimization
- Build & Fix - Validate through actual build, fix errors iteratively
- Runtime Validation - Verify migrations ran, app works, database populated
本工具通过四步流程生成可用于生产环境的Dockerfile:
- 深度分析 - 理解项目结构、工作区、迁移脚本和构建复杂度
- 生成 - 创建包含迁移处理和构建优化的Dockerfile
- 构建与修复 - 通过实际构建验证效果,迭代修复错误
- 运行时验证 - 确认迁移执行成功、应用正常运行、数据库已填充数据
Key Capabilities
核心功能
- Workspace/Monorepo Support: pnpm workspace, Turborepo, npm workspaces
- Custom CLI Detection: Auto-detect custom build CLIs (turbo, nx, lerna, rush, or project-specific) and use correct syntax
- Git Hash Bypass: Detect and handle projects requiring git commit hash (GITHUB_SHA)
- Build-Time Env Vars: Auto-detect and add placeholders for Next.js SSG
- Error Pattern Database: 40+ known error patterns with automatic fixes
- Smart .dockerignore: Avoid excluding workspace-required files and CLI config dependencies
- Custom Entry Points: Support for custom server launchers
- Migration Detection: Auto-detect ORM, migrations, handle standalone mode
- Build Optimization: Skip heavy CI tasks (lint/type-check) to prevent OOM
- Runtime Validation: Verify migrations ran, database populated, app working
- Native Module Support: Auto-detect Rust/NAPI-RS modules, multi-architecture builds
- Static Asset Mapping: Detect backend's expected static paths and map frontend outputs
- External Services: Auto-detect PostgreSQL, Redis, MinIO, ManticoreSearch dependencies
- Zero Human Interaction: Auto-generate all config files including secrets
- 工作区/Monorepo支持:支持pnpm workspace、Turborepo、npm workspaces
- 自定义CLI检测:自动识别自定义构建CLI(turbo、nx、lerna、rush或项目专属CLI)并使用正确语法
- Git哈希绕过:识别并处理需要git提交哈希(GITHUB_SHA)的项目
- 构建时环境变量:自动识别并为Next.js SSG添加占位符
- 错误模式数据库:内置40+已知错误模式,可自动修复
- 智能.dockerignore:避免排除工作区所需文件和CLI配置依赖
- 自定义入口点:支持自定义服务启动器
- 迁移脚本检测:自动识别ORM、迁移脚本,支持独立模式
- 构建优化:跳过lint/类型检查等重型CI任务,避免内存溢出
- 运行时验证:确认迁移执行成功、数据库已填充、应用正常运行
- 原生模块支持:自动识别Rust/NAPI-RS模块,支持多架构构建
- 静态资源映射:识别后端预期的静态资源路径,映射前端构建产物
- 外部服务识别:自动检测PostgreSQL、Redis、MinIO、ManticoreSearch依赖
- 零人工干预:自动生成所有配置文件,包括密钥配置
Usage
使用方法
/dockerfile # Analyze current directory
/dockerfile <github-url> # Clone and analyze GitHub repo
/dockerfile <path> # Analyze specific path/dockerfile # 分析当前目录
/dockerfile <github-url> # 克隆并分析GitHub仓库
/dockerfile <path> # 分析指定路径Quick Start
快速开始
When invoked, ALWAYS follow this sequence:
- Read and execute modules/analyze.md
- Read and execute modules/generate.md
- Read and execute modules/build-fix.md
被调用时,请务必遵循以下顺序执行:
- 读取并执行 modules/analyze.md
- 读取并执行 modules/generate.md
- 读取并执行 modules/build-fix.md
Workflow
工作流程
Phase 1: Deep Project Analysis
阶段1:深度项目分析
Load and execute: modules/analyze.md
Output: Structured project metadata including:
- Language / Framework / Package manager
- Build commands / Run commands / Port
- External dependencies (DB/Redis/S3)
- System library requirements
- Migration system detection (ORM, migration count, execution method)
- Build complexity analysis (heavy operations, memory risk)
- Complexity level (L1/L2/L3)
加载并执行:modules/analyze.md
输出:结构化的项目元数据,包含:
- 语言/框架/包管理器
- 构建命令/运行命令/端口
- 外部依赖(数据库/Redis/S3)
- 系统库依赖要求
- 迁移系统检测(ORM、迁移数量、执行方式)
- 构建复杂度分析(重型操作、内存风险)
- 复杂度等级(L1/L2/L3)
Phase 2: Generate Dockerfile
阶段2:生成Dockerfile
Load and execute: modules/generate.md
Input: Analysis result from Phase 1
Output:
- (with migration handling, build optimization)
Dockerfile - (workspace-aware)
.dockerignore - (if external services needed)
docker-compose.yml - (auto-generated with test secrets)
.env.docker.local - (with migration execution)
docker-entrypoint.sh - (complete deployment guide)
DOCKER.md - Environment variable documentation
Key Enhancements:
- Auto-detect Next.js Standalone + ORM → separate deps installation
- Auto-detect heavy build operations → optimized build command
- Auto-generate all config files → zero user input required
加载并执行:modules/generate.md
输入:阶段1的分析结果
输出:
- (包含迁移处理、构建优化)
Dockerfile - (适配工作区规则)
.dockerignore - (如果需要外部服务)
docker-compose.yml - (自动生成的测试密钥配置)
.env.docker.local - (包含迁移执行逻辑)
docker-entrypoint.sh - (完整部署指南)
DOCKER.md - 环境变量文档
核心优化:
- 自动识别Next.js Standalone + ORM → 单独安装依赖
- 自动识别重型构建操作 → 优化构建命令
- 自动生成所有配置文件 → 无需用户输入
Phase 3: Build Validation (Closed Loop)
阶段3:构建验证(闭环)
Load and execute: modules/build-fix.md
Process:
- Execute
docker buildx build --platform linux/amd64 --load - If success → Proceed to Phase 4
- If failure → Parse error, match pattern, fix Dockerfile, retry
- Max iterations based on complexity level
加载并执行:modules/build-fix.md
流程:
- 执行
docker buildx build --platform linux/amd64 --load - 构建成功 → 进入阶段4
- 构建失败 → 解析错误、匹配模式、修复Dockerfile、重试
- 最大重试次数根据复杂度等级确定
Phase 4: Runtime Validation
阶段4:运行时验证
Critical Addition: Don't declare success until runtime verification passes!
Validation Steps:
- Container Startup: and verify no crashes
docker-compose up -d - Database Migration:
- Query database: → verify tables exist
psql -c "\dt" - Check migration count matches expected (e.g., 76/76)
- Verify no "relation does not exist" errors
- Application Health:
- Test HTTP endpoint → 200/302/401 acceptable, 500 is failure
- Check logs for errors
- Verify health check endpoint
- Success Criteria: Only declare success if ALL pass
Why This Matters:
- Previous: Declared success after , but app didn't work at runtime
docker build - Now: Verify migrations ran, database populated, app actually functional
- Prevents silent migration failures (e.g., standalone mode missing ORM deps)
核心要求:运行时验证通过前,不得宣告成功!
验证步骤:
- 容器启动:执行 ,确认无崩溃
docker-compose up -d - 数据库迁移验证:
- 查询数据库:→ 确认表存在
psql -c "\dt" - 检查迁移数量匹配预期(例如76/76)
- 确认无"relation does not exist"错误
- 应用健康检查:
- 测试HTTP接口 → 200/302/401为可接受状态,500为失败
- 检查日志无错误
- 确认健康检查接口正常
- 成功标准:所有验证项全部通过才宣告成功
重要性说明:
- 旧方案:成功就宣告成功,但运行时应用可能无法工作
docker build - 新方案:验证迁移执行成功、数据库已填充、应用实际可运行
- 避免静默迁移失败(例如独立模式缺失ORM依赖的问题)
Supporting Resources
支持资源
- Templates: templates/ - Base Dockerfile templates by tech stack
- Error Patterns: knowledge/error-patterns.md - Known errors and fixes
- System Dependencies: knowledge/system-deps.md - NPM/Pip package → system library mapping
- Best Practices: knowledge/best-practices.md - Docker production best practices
- Output Format: examples/output-format.md - Expected output structure
- 模板:templates/ - 按技术栈分类的基础Dockerfile模板
- 错误模式:knowledge/error-patterns.md - 已知错误及解决方案
- 系统依赖:knowledge/system-deps.md - NPM/Pip包与系统库的映射关系
- 最佳实践:knowledge/best-practices.md - Docker生产环境最佳实践
- 输出格式:examples/output-format.md - 预期输出结构
Complexity Levels
复杂度等级
| Level | Criteria | Max Build Iterations |
|---|---|---|
| L1 | Single language, no build step, no external services, no migrations | 1 |
| L2 | Has build step, has external services (DB/Redis), simple migrations | 3 |
| L3 | Monorepo, multi-language, complex dependencies, build-time env vars, complex migrations (76+) | 5 |
| 等级 | 判断标准 | 最大构建重试次数 |
|---|---|---|
| L1 | 单一语言、无构建步骤、无外部服务、无迁移脚本 | 1 |
| L2 | 有构建步骤、有外部服务(数据库/Redis)、简单迁移 | 3 |
| L3 | Monorepo、多语言、复杂依赖、构建时环境变量、复杂迁移(76条以上) | 5 |
Common Issues & Solutions
常见问题与解决方案
1. Database migrations not running - MOST CRITICAL
1. 数据库迁移未执行 - 最高优先级
Symptom: at runtime
Cause: Migrations detected but never executed
Prevention: Analysis phase Step 12 detects migrations and configures execution
Fix:
relation "users" does not exist- For Standalone + ORM: Install ORM deps separately
- Add runtime migration to entrypoint script
- Verify with after container starts
psql -c "\dt"
症状:运行时报错误
原因:识别到迁移脚本但未执行
预防方案:分析阶段第12步检测迁移脚本并配置执行逻辑
修复方案:
relation "users" does not exist- 独立模式+ORM场景:单独安装ORM依赖
- 在入口点脚本中添加运行时迁移逻辑
- 容器启动后通过验证
psql -c "\dt"
2. Out of Memory during build
2. 构建时内存溢出
Symptom: Exit code 137, , heap out of memory
Cause: Build script includes lint/type-check for 39+ workspace packages
Prevention: Analysis phase Step 13 detects heavy operations
Fix: Skip CI tasks in Docker build, increase NODE_OPTIONS to 8192MB
Killed症状:退出码137、提示、堆内存溢出
原因:构建脚本包含39个以上工作区包的lint/类型检查任务
预防方案:分析阶段第13步检测重型操作
修复方案:Docker构建中跳过CI任务,将NODE_OPTIONS调整为8192MB
Killed3. Workspace files not found
3. 工作区文件找不到
Symptom:
Cause: .dockerignore excludes workspace package.json files
Fix: Use instead of , then
ENOENT: no such file or directory, open '/app/e2e/package.json'e2e/*e2e!e2e/package.json症状:
原因:.dockerignore排除了工作区的package.json文件
修复方案:使用替代规则,再添加规则
ENOENT: no such file or directory, open '/app/e2e/package.json'e2e/*e2e!e2e/package.json4. lockfile=false projects
4. 配置lockfile=false的项目
Symptom:
Cause: Project has in .npmrc
Fix: Use instead of
Cannot generate lockfile because lockfile is set to falselockfile=falsepnpm installpnpm install --frozen-lockfile症状:
原因:项目.npmrc中配置了
修复方案:使用替代
Cannot generate lockfile because lockfile is set to falselockfile=falsepnpm installpnpm install --frozen-lockfile5. Build-time env vars missing
5. 构建时环境变量缺失
Symptom:
Cause: Next.js SSG needs env vars at build time
Fix: Add ARG/ENV placeholders in build stage
KEY_VAULTS_SECRET is not set症状:
原因:Next.js SSG在构建时需要环境变量
修复方案:在构建阶段添加ARG/ENV占位符
KEY_VAULTS_SECRET is not set6. Node binary path
6. Node二进制路径错误
Symptom:
Cause: Scripts hardcode but has it at
Fix: Add
spawn /bin/node ENOENT/bin/nodenode:slim/usr/local/bin/nodeRUN ln -sf /usr/local/bin/node /bin/node症状:
原因:脚本硬编码了路径,但镜像中node路径为
修复方案:添加规则
spawn /bin/node ENOENT/bin/nodenode:slim/usr/local/bin/nodeRUN ln -sf /usr/local/bin/node /bin/node7. ORM not found in Standalone mode
7. 独立模式下找不到ORM
Symptom: at runtime
Cause: Next.js standalone doesn't include all node_modules
Prevention: Analysis phase detects standalone + ORM combination
Fix: Install ORM separately in /deps and copy to final image
Cannot find module 'drizzle-orm'症状:运行时报错误
原因:Next.js standalone模式未包含全部node_modules
预防方案:分析阶段检测独立模式+ORM的组合场景
修复方案:在/deps目录单独安装ORM,再复制到最终镜像
Cannot find module 'drizzle-orm'8. Wrong build command for monorepo with custom CLI
8. 带自定义CLI的Monorepo构建命令错误
Symptom: Build succeeds but output files missing (e.g., not found)
Cause: Using instead of detected custom CLI syntax
Prevention: Analysis phase Step 14 detects custom CLI
Fix: Use detected CLI syntax for all build commands
assets-manifest.jsonyarn workspace @scope/pkg build症状:构建成功但产物缺失(例如找不到)
原因:使用了而非识别到的自定义CLI语法
预防方案:分析阶段第14步检测自定义CLI
修复方案:所有构建命令使用识别到的CLI语法
assets-manifest.jsonyarn workspace @scope/pkg build9. Git hash required but .git not in Docker context
9. 需要Git哈希但Docker上下文不包含.git目录
Symptom: or errors
Cause: Build tool requires git commit hash for versioning
Prevention: Analysis phase Step 14 detects git hash dependency
Fix: Set to bypass git requirement
Failed to open git reponodegitENV GITHUB_SHA=docker-build症状:或错误
原因:构建工具需要git提交哈希用于版本管理
预防方案:分析阶段第14步检测Git哈希依赖
修复方案:设置绕过Git要求
Failed to open git reponodegitENV GITHUB_SHA=docker-build10. CLI config files excluded by .dockerignore
10. CLI配置文件被.dockerignore排除
Symptom: CLI initialization (e.g., ) fails silently
Cause: , , or other config files excluded
Prevention: Analysis phase Step 14 detects config file dependencies
Fix: Remove config files from .dockerignore exclusions
${CLI_NAME} init.prettierrc.prettierignore症状:CLI初始化(例如)静默失败
原因:、或其他配置文件被排除
预防方案:分析阶段第14步检测配置文件依赖
修复方案:从.dockerignore排除规则中移除相关配置文件
${CLI_NAME} init.prettierrc.prettierignore11. Static assets not found at runtime
11. 运行时找不到静态资源
Symptom:
Cause: Frontend builds to different path than backend expects
Prevention: Analysis phase Step 14 detects static asset path mapping
Fix: Copy frontend outputs to backend's expected path in Dockerfile
ENOENT: no such file or directory, open '/app/static/assets-manifest.json'症状:
原因:前端构建产物路径与后端预期路径不匹配
预防方案:分析阶段第14步检测静态资源路径映射关系
修复方案:在Dockerfile中将前端产物复制到后端预期路径
ENOENT: no such file or directory, open '/app/static/assets-manifest.json'Success Criteria
成功标准
A successful Dockerfile must:
Build Phase:
- Build without errors (exits 0)
docker buildx build - Image size reasonable (< 2GB for most apps)
- Follow production best practices (multi-stage, non-root, fixed versions)
- Include all necessary supporting files (.dockerignore, docker-compose.yml, etc.)
- Handle all workspace/monorepo requirements
Runtime Phase - CRITICAL:
6. Container starts successfully (no crashes)
7. Database migrations execute successfully (if migrations detected)
8. Database tables created (verify with psql)
9. Application responds with valid HTTP codes (200/302/401, not 500)
10. No runtime errors in logs (no "relation does not exist", etc.)
DO NOT declare success if:
- Build passes but runtime fails
- Migrations detected but tables missing
- App returns 500 errors
- Logs show database relation errors
合格的Dockerfile必须满足:
构建阶段:
- 无错误构建完成(退出码为0)
docker buildx build - 镜像大小合理(大多数应用小于2GB)
- 遵循生产最佳实践(多阶段构建、非root用户、版本固定)
- 包含所有必要的配套文件(.dockerignore、docker-compose.yml等)
- 满足所有工作区/Monorepo要求
运行时阶段 - 核心要求:
6. 容器启动成功(无崩溃)
7. 数据库迁移执行成功(如果检测到迁移脚本)
8. 数据库表已创建(通过psql验证)
9. 应用返回合法HTTP状态码(200/302/401,非500)
10. 日志无运行时错误(无"relation does not exist"等错误)
出现以下情况不得宣告成功:
- 构建通过但运行时失败
- 检测到迁移脚本但表缺失
- 应用返回500错误
- 日志显示数据库关联错误
Post-Build Validation COMPREHENSIVE
构建后全量验证
After successful build, perform FULL validation:
bash
undefined构建成功后,执行完整验证流程:
bash
undefined1. Start services
1. 启动服务
docker-compose up -d
sleep 30 # Wait for startup
docker-compose up -d
sleep 30 # 等待启动完成
2. Check container status
2. 检查容器状态
docker-compose ps
docker-compose ps
Expected: All containers UP and HEALTHY
预期:所有容器状态为UP且HEALTHY
3. Verify database migrations
3. 验证数据库迁移
if [ migrations_detected ]; then
List tables
docker-compose exec postgres psql -U <user> -d <db> -c "\dt"
Expected: List of tables (users, sessions, etc.)
If "Did not find any relations" → FAIL
Count migrations
MIGRATION_COUNT=$(docker-compose exec postgres psql -U <user> -d <db> -t -c "SELECT COUNT(*) FROM <migration_table>;")
Expected: Matches analysis count (e.g., 76)
fi
if [ migrations_detected ]; then
列出所有表
docker-compose exec postgres psql -U <user> -d <db> -c "\dt"
预期:存在用户、会话等表
如果返回"Did not find any relations" → 验证失败
统计迁移数量
MIGRATION_COUNT=$(docker-compose exec postgres psql -U <user> -d <db> -t -c "SELECT COUNT(*) FROM <migration_table>;")
预期:与分析阶段统计的迁移数量一致(例如76)
fi
4. Test application health
4. 测试应用健康状态
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3210)
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3210)
Expected: 200, 302, or 401
预期:200、302或401
Unacceptable: 500, 502, 503
不可接受:500、502、503
if [ "$HTTP_CODE" = "500" ]; then
echo "FAILURE: App returning 500 error"
docker-compose logs app
exit 1
fi
if [ "$HTTP_CODE" = "500" ]; then
echo "FAILURE: App returning 500 error"
docker-compose logs app
exit 1
fi
5. Check for errors in logs
5. 检查日志是否存在错误
docker-compose logs app | grep -i "error" | tail -20
docker-compose logs app | grep -i "error" | tail -20
Should NOT contain:
不得包含以下内容:
- "relation does not exist"
- "relation does not exist"
- "table not found"
- "table not found"
- "Cannot find module"
- "Cannot find module"
6. Check image size
6. 检查镜像大小
docker images <image-name>
docker images <image-name>
7. Cleanup (if needed)
7. 清理资源(按需)
docker-compose down
**Validation Checklist**:
- [ ] Image built successfully
- [ ] Container started without crashes
- [ ] Database connection established
- [ ] **Migrations executed (if applicable)**
- [ ] **Database tables exist (if applicable)**
- [ ] HTTP endpoint returns valid status
- [ ] No errors in application logs
- [ ] Health check passesdocker-compose down
**验证清单**:
- [ ] 镜像构建成功
- [ ] 容器启动无崩溃
- [ ] 数据库连接正常
- [ ] **迁移执行成功(如有)**
- [ ] **数据库表存在(如有)**
- [ ] HTTP接口返回合法状态码
- [ ] 应用日志无错误
- [ ] 健康检查通过