dockerfile-skill

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dockerfile Generator Skill

Dockerfile生成工具

Overview

概述

This skill generates production-ready Dockerfiles through a 4-phase process:
  1. Deep Analysis - Understand project structure, workspace, migrations, and build complexity
  2. Generate - Create Dockerfile with migration handling and build optimization
  3. Build & Fix - Validate through actual build, fix errors iteratively
  4. Runtime Validation - Verify migrations ran, app works, database populated
本工具通过四步流程生成可用于生产环境的Dockerfile:
  1. 深度分析 - 理解项目结构、工作区、迁移脚本和构建复杂度
  2. 生成 - 创建包含迁移处理和构建优化的Dockerfile
  3. 构建与修复 - 通过实际构建验证效果,迭代修复错误
  4. 运行时验证 - 确认迁移执行成功、应用正常运行、数据库已填充数据

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:
  1. Read and execute modules/analyze.md
  2. Read and execute modules/generate.md
  3. Read and execute modules/build-fix.md
被调用时,请务必遵循以下顺序执行:
  1. 读取并执行 modules/analyze.md
  2. 读取并执行 modules/generate.md
  3. 读取并执行 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:
  • Dockerfile
    (with migration handling, build optimization)
  • .dockerignore
    (workspace-aware)
  • docker-compose.yml
    (if external services needed)
  • .env.docker.local
    (auto-generated with test secrets)
  • docker-entrypoint.sh
    (with migration execution)
  • DOCKER.md
    (complete deployment guide)
  • 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:
  1. Execute
    docker buildx build --platform linux/amd64 --load
  2. If success → Proceed to Phase 4
  3. If failure → Parse error, match pattern, fix Dockerfile, retry
  4. Max iterations based on complexity level
加载并执行:modules/build-fix.md
流程
  1. 执行
    docker buildx build --platform linux/amd64 --load
  2. 构建成功 → 进入阶段4
  3. 构建失败 → 解析错误、匹配模式、修复Dockerfile、重试
  4. 最大重试次数根据复杂度等级确定

Phase 4: Runtime Validation

阶段4:运行时验证

Critical Addition: Don't declare success until runtime verification passes!
Validation Steps:
  1. Container Startup:
    docker-compose up -d
    and verify no crashes
  2. Database Migration:
  • Query database:
    psql -c "\dt"
    → verify tables exist
  • Check migration count matches expected (e.g., 76/76)
  • Verify no "relation does not exist" errors
  1. Application Health:
  • Test HTTP endpoint → 200/302/401 acceptable, 500 is failure
  • Check logs for errors
  • Verify health check endpoint
  1. Success Criteria: Only declare success if ALL pass
Why This Matters:
  • Previous: Declared success after
    docker build
    , but app didn't work at runtime
  • Now: Verify migrations ran, database populated, app actually functional
  • Prevents silent migration failures (e.g., standalone mode missing ORM deps)
核心要求:运行时验证通过前,不得宣告成功!
验证步骤
  1. 容器启动:执行
    docker-compose up -d
    ,确认无崩溃
  2. 数据库迁移验证
  • 查询数据库:
    psql -c "\dt"
    → 确认表存在
  • 检查迁移数量匹配预期(例如76/76)
  • 确认无"relation does not exist"错误
  1. 应用健康检查
  • 测试HTTP接口 → 200/302/401为可接受状态,500为失败
  • 检查日志无错误
  • 确认健康检查接口正常
  1. 成功标准:所有验证项全部通过才宣告成功
重要性说明
  • 旧方案:
    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

复杂度等级

LevelCriteriaMax Build Iterations
L1Single language, no build step, no external services, no migrations1
L2Has build step, has external services (DB/Redis), simple migrations3
L3Monorepo, multi-language, complex dependencies, build-time env vars, complex migrations (76+)5
等级判断标准最大构建重试次数
L1单一语言、无构建步骤、无外部服务、无迁移脚本1
L2有构建步骤、有外部服务(数据库/Redis)、简单迁移3
L3Monorepo、多语言、复杂依赖、构建时环境变量、复杂迁移(76条以上)5

Common Issues & Solutions

常见问题与解决方案

1. Database migrations not running - MOST CRITICAL

1. 数据库迁移未执行 - 最高优先级

Symptom:
relation "users" does not exist
at runtime Cause: Migrations detected but never executed Prevention: Analysis phase Step 12 detects migrations and configures execution Fix:
  • For Standalone + ORM: Install ORM deps separately
  • Add runtime migration to entrypoint script
  • Verify with
    psql -c "\dt"
    after container starts
症状:运行时报
relation "users" does not exist
错误 原因:识别到迁移脚本但未执行 预防方案:分析阶段第12步检测迁移脚本并配置执行逻辑 修复方案
  • 独立模式+ORM场景:单独安装ORM依赖
  • 在入口点脚本中添加运行时迁移逻辑
  • 容器启动后通过
    psql -c "\dt"
    验证

2. Out of Memory during build

2. 构建时内存溢出

Symptom: Exit code 137,
Killed
, 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
症状:退出码137、
Killed
提示、堆内存溢出 原因:构建脚本包含39个以上工作区包的lint/类型检查任务 预防方案:分析阶段第13步检测重型操作 修复方案:Docker构建中跳过CI任务,将NODE_OPTIONS调整为8192MB

3. Workspace files not found

3. 工作区文件找不到

Symptom:
ENOENT: no such file or directory, open '/app/e2e/package.json'
Cause: .dockerignore excludes workspace package.json files Fix: Use
e2e/*
instead of
e2e
, then
!e2e/package.json
症状
ENOENT: no such file or directory, open '/app/e2e/package.json'
原因:.dockerignore排除了工作区的package.json文件 修复方案:使用
e2e/*
替代
e2e
规则,再添加
!e2e/package.json
规则

4. lockfile=false projects

4. 配置lockfile=false的项目

Symptom:
Cannot generate lockfile because lockfile is set to false
Cause: Project has
lockfile=false
in .npmrc Fix: Use
pnpm install
instead of
pnpm install --frozen-lockfile
症状
Cannot generate lockfile because lockfile is set to false
原因:项目.npmrc中配置了
lockfile=false
修复方案:使用
pnpm install
替代
pnpm install --frozen-lockfile

5. Build-time env vars missing

5. 构建时环境变量缺失

Symptom:
KEY_VAULTS_SECRET is not set
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占位符

6. Node binary path

6. Node二进制路径错误

Symptom:
spawn /bin/node ENOENT
Cause: Scripts hardcode
/bin/node
but
node:slim
has it at
/usr/local/bin/node
Fix: Add
RUN ln -sf /usr/local/bin/node /bin/node
症状
spawn /bin/node ENOENT
原因:脚本硬编码了
/bin/node
路径,但
node:slim
镜像中node路径为
/usr/local/bin/node
修复方案:添加
RUN ln -sf /usr/local/bin/node /bin/node
规则

7. ORM not found in Standalone mode

7. 独立模式下找不到ORM

Symptom:
Cannot find module 'drizzle-orm'
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,再复制到最终镜像

8. Wrong build command for monorepo with custom CLI

8. 带自定义CLI的Monorepo构建命令错误

Symptom: Build succeeds but output files missing (e.g.,
assets-manifest.json
not found) Cause: Using
yarn workspace @scope/pkg build
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.json
原因:使用了
yarn workspace @scope/pkg build
而非识别到的自定义CLI语法 预防方案:分析阶段第14步检测自定义CLI 修复方案:所有构建命令使用识别到的CLI语法

9. Git hash required but .git not in Docker context

9. 需要Git哈希但Docker上下文不包含.git目录

Symptom:
Failed to open git repo
or
nodegit
errors Cause: Build tool requires git commit hash for versioning Prevention: Analysis phase Step 14 detects git hash dependency Fix: Set
ENV GITHUB_SHA=docker-build
to bypass git requirement
症状
Failed to open git repo
nodegit
错误 原因:构建工具需要git提交哈希用于版本管理 预防方案:分析阶段第14步检测Git哈希依赖 修复方案:设置
ENV GITHUB_SHA=docker-build
绕过Git要求

10. CLI config files excluded by .dockerignore

10. CLI配置文件被.dockerignore排除

Symptom: CLI initialization (e.g.,
${CLI_NAME} init
) fails silently Cause:
.prettierrc
,
.prettierignore
, or other config files excluded Prevention: Analysis phase Step 14 detects config file dependencies Fix: Remove config files from .dockerignore exclusions
症状:CLI初始化(例如
${CLI_NAME} init
)静默失败 原因
.prettierrc
.prettierignore
或其他配置文件被排除 预防方案:分析阶段第14步检测配置文件依赖 修复方案:从.dockerignore排除规则中移除相关配置文件

11. Static assets not found at runtime

11. 运行时找不到静态资源

Symptom:
ENOENT: no such file or directory, open '/app/static/assets-manifest.json'
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中将前端产物复制到后端预期路径

Success Criteria

成功标准

A successful Dockerfile must:
Build Phase:
  1. Build without errors (
    docker buildx build
    exits 0)
  2. Image size reasonable (< 2GB for most apps)
  3. Follow production best practices (multi-stage, non-root, fixed versions)
  4. Include all necessary supporting files (.dockerignore, docker-compose.yml, etc.)
  5. 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必须满足:
构建阶段
  1. 无错误构建完成(
    docker buildx build
    退出码为0)
  2. 镜像大小合理(大多数应用小于2GB)
  3. 遵循生产最佳实践(多阶段构建、非root用户、版本固定)
  4. 包含所有必要的配套文件(.dockerignore、docker-compose.yml等)
  5. 满足所有工作区/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
undefined

1. 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 passes
docker-compose down

**验证清单**:
- [ ] 镜像构建成功
- [ ] 容器启动无崩溃
- [ ] 数据库连接正常
- [ ] **迁移执行成功(如有)**
- [ ] **数据库表存在(如有)**
- [ ] HTTP接口返回合法状态码
- [ ] 应用日志无错误
- [ ] 健康检查通过