docker
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDocker
Docker
Production-grade Docker containerization with security-first defaults.
采用安全优先默认配置的生产级Docker容器化方案。
Resource Detection & Adaptation
资源检测与适配
Before generating Dockerfiles/Compose, detect the environment:
bash
undefined生成Dockerfile/Compose之前,先检测环境:
bash
undefinedDetect host machine memory
检测主机内存
sysctl -n hw.memsize 2>/dev/null | awk '{print $0/1024/1024/1024 " GB"}' ||
grep MemTotal /proc/meminfo | awk '{print $2/1024/1024 " GB"}'
grep MemTotal /proc/meminfo | awk '{print $2/1024/1024 " GB"}'
sysctl -n hw.memsize 2>/dev/null | awk '{print $0/1024/1024/1024 " GB"}' ||
grep MemTotal /proc/meminfo | awk '{print $2/1024/1024 " GB"}'
grep MemTotal /proc/meminfo | awk '{print $2/1024/1024 " GB"}'
Detect Docker allocated resources
检测Docker分配的资源
docker info --format 'Memory: {{.MemTotal}}, CPUs: {{.NCPU}}'
docker info --format 'Memory: {{.MemTotal}}, CPUs: {{.NCPU}}'
Detect available disk space
检测可用磁盘空间
docker system df
**Adapt configurations based on detection:**
| Detected Docker Memory | Profile | Build Memory | Container Limits |
|-----------------------|---------|--------------|------------------|
| < 4GB | Constrained | 1GB | 256Mi |
| 4-8GB | Minimal | 2GB | 512Mi |
| 8-12GB | Standard | 4GB | 1Gi |
| > 12GB | Extended | 8GB | 2Gi |docker system df
**根据检测结果适配配置:**
| 检测到的Docker内存 | 配置文件 | 构建内存 | 容器限制 |
|-----------------------|---------|--------------|------------------|
| < 4GB | 受限模式 | 1GB | 256Mi |
| 4-8GB | 最小模式 | 2GB | 512Mi |
| 8-12GB | 标准模式 | 4GB | 1Gi |
| > 12GB | 扩展模式 | 8GB | 2Gi |Agent Behavior
Agent行为
- Detect Docker resources before generating compose.yaml
- Adapt resource limits to available memory
- Warn if build may fail due to insufficient resources
- Calculate safe limits:
docker_memory * 0.6 / container_count
- 检测:生成compose.yaml之前先检测Docker资源
- 适配:根据可用内存调整资源限制
- 警告:如果资源不足可能导致构建失败,发出警告
- 计算:安全限制公式:
docker_memory * 0.6 / container_count
Adaptive Compose Templates
自适应Compose模板
Constrained (< 4GB Docker):
yaml
services:
app:
deploy:
resources:
limits:
memory: 256M
cpus: '0.25'
build:
args:
- BUILDKIT_STEP_LOG_MAX_SIZE=10000000⚠️ Agent should warn: "Docker memory low. Multi-stage builds may fail."
Standard (4-8GB Docker):
yaml
services:
app:
deploy:
resources:
limits:
memory: 512M
cpus: '0.5'
reservations:
memory: 256MExtended (> 8GB Docker):
yaml
services:
app:
deploy:
resources:
limits:
memory: 1G
cpus: '1.0'
reservations:
memory: 512M受限模式(Docker内存<4GB):
yaml
services:
app:
deploy:
resources:
limits:
memory: 256M
cpus: '0.25'
build:
args:
- BUILDKIT_STEP_LOG_MAX_SIZE=10000000⚠️ Agent应发出警告:"Docker内存不足。多阶段构建可能失败。"
标准模式(Docker内存4-8GB):
yaml
services:
app:
deploy:
resources:
limits:
memory: 512M
cpus: '0.5'
reservations:
memory: 256M扩展模式(Docker内存>8GB):
yaml
services:
app:
deploy:
resources:
limits:
memory: 1G
cpus: '1.0'
reservations:
memory: 512MPre-Build Validation
构建前验证
Before running , agent should verify:
docker buildbash
undefined运行之前,Agent应执行以下验证:
docker buildbash
undefinedCheck available memory
检查可用内存
docker info --format '{{.MemTotal}}' | awk '{if ($1 < 4000000000) print "WARNING: Low memory"}'
If constrained: use `--memory` flag and warn user about potential build failures.
---docker info --format '{{.MemTotal}}' | awk '{if ($1 < 4000000000) print "WARNING: Low memory"}'
如果处于受限模式:使用`--memory`参数,并警告用户可能出现构建失败。
---What This Skill Does
该技能的功能
Analysis & Detection:
- Auto-detects runtime, framework, version, entrypoint (no questions)
- Scans .env files, classifies secrets vs build-args vs runtime config
- Detects native dependencies, generates correct build deps
- Identifies missing configs (Next.js standalone, health endpoints)
Generation:
- Creates multi-stage Dockerfiles customized to YOUR project structure
- Generates compose.yaml with security defaults (non-root, read-only, resource limits)
- Adds health endpoints if missing
- Fixes configuration issues (adds to Next.js, etc.)
output: 'standalone'
Validation:
- Builds both dev and production targets before delivering
- Verifies health endpoints work
- Confirms non-root user in production
- Warns about any secrets that would leak into image
- Reports image size
Security:
- Never bakes secrets into images
- Non-root user by default
- Minimal attack surface (multi-stage builds)
- Pinned versions (no )
:latest - Security scan command included
分析与检测:
- 自动检测运行时、框架、版本、入口点(无需提问)
- 扫描.env文件,区分敏感信息、构建参数与运行时配置
- 检测原生依赖,生成正确的构建依赖
- 识别缺失的配置(如Next.js standalone、健康检查端点)
生成:
- 创建针对您项目结构定制的多阶段Dockerfile
- 生成带有安全默认配置的compose.yaml(非root用户、只读模式、资源限制)
- 如果缺失则添加健康检查端点
- 修复配置问题(如为Next.js添加等)
output: 'standalone'
验证:
- 交付前构建开发和生产两种目标镜像
- 验证健康检查端点是否正常工作
- 确认生产环境使用非root用户
- 警告可能会泄露到镜像中的敏感信息
- 报告镜像大小
安全:
- 绝不会将敏感信息嵌入镜像
- 默认使用非root用户
- 最小化攻击面(多阶段构建)
- 固定版本(不使用标签)
:latest - 包含安全扫描命令
What This Skill Does NOT Do
该技能不支持的功能
- Generate Kubernetes manifests (use dedicated k8s skill)
- Create Helm charts (use dedicated helm skill)
- Handle Bun/Deno (use dedicated skills)
- Copy templates blindly without customization
- 生成Kubernetes清单(请使用专门的k8s技能)
- 创建Helm Chart(请使用专门的Helm技能)
- 处理Bun/Deno(请使用专门的技能)
- 盲目复制模板而不进行定制
Before Implementation
实施前准备
Gather context to ensure successful implementation:
| Source | Gather |
|---|---|
| Codebase | Package files, existing Dockerfile, .env patterns |
| Conversation | Dev vs production target, base image preferences |
| Skill References | Framework patterns, multi-stage builds, security |
| User Guidelines | Registry conventions, naming standards |
收集上下文信息以确保实施成功:
| 来源 | 收集内容 |
|---|---|
| 代码库 | 包文件、现有Dockerfile、.env文件模式 |
| 对话记录 | 开发或生产目标、基础镜像偏好 |
| 技能参考 | 框架模式、多阶段构建、安全规范 |
| 用户指南 | 镜像仓库约定、命名标准 |
Required Clarifications
需要确认的信息
Ask when not auto-detectable:
| Question | When to Ask |
|---|---|
| Target environment | "Building for development or production?" |
| Base image preference | "Standard slim images or enterprise hardened?" |
| Existing Docker files | "Enhance existing Dockerfile or create new?" |
| Registry target | "Local only or pushing to registry?" |
当无法自动检测时,需询问用户:
| 问题 | 询问时机 |
|---|---|
| 目标环境 | "是为开发环境还是生产环境构建?" |
| 基础镜像偏好 | "使用标准slim镜像还是企业级加固镜像?" |
| 现有Docker文件 | "是优化现有Dockerfile还是创建新的?" |
| 目标镜像仓库 | "仅本地使用还是推送到镜像仓库?" |
Detect Runtime
检测运行时
| File Present | Runtime | Package Manager |
|---|---|---|
| Python | pip/uv |
| Node.js | pnpm |
| Node.js | yarn |
| Node.js | npm |
| 存在的文件 | 运行时 | 包管理器 |
|---|---|---|
| Python | pip/uv |
| Node.js | pnpm |
| Node.js | yarn |
| Node.js | npm |
Auto-Detection (Do NOT ask - detect from files)
自动检测(无需询问 - 从文件中检测)
Python
Python
| What | Detect From |
|---|---|
| Python version | |
| Framework | Imports in code ( |
| Package manager | |
| Native deps | Scan requirements: |
| App entrypoint | Find |
| 检测内容 | 检测来源 |
|---|---|
| Python版本 | |
| 框架 | 代码中的导入语句( |
| 包管理器 | |
| 原生依赖 | 扫描requirements文件: |
| 应用入口点 | 查找 |
Node.js
Node.js
| What | Detect From |
|---|---|
| Node version | |
| Framework | |
| Package manager | |
| Output type | Next.js: check |
| 检测内容 | 检测来源 |
|---|---|
| Node版本 | |
| 框架 | |
| 包管理器 | |
| 输出类型 | Next.js:检查 |
Fix Issues Automatically
自动修复问题
| Issue | Action |
|---|---|
Next.js missing | Add it to next.config.js |
| No health endpoint found | Create |
| Using uv but no uv.lock | Run |
| pyproject.toml but no build system | Use |
| 问题 | 操作 |
|---|---|
Next.js缺失 | 添加到next.config.js |
| 未找到健康检查端点 | 创建 |
| 使用uv但无uv.lock | 先运行 |
| 存在pyproject.toml但无构建系统 | 使用 |
Workflow
工作流程
1. SCAN PROJECT
- Detect runtime, framework, version, entrypoint
- Find dependency files, native deps
- Locate existing Docker files (don't blindly overwrite)
↓
2. ANALYZE ENVIRONMENT
- Scan all .env* files
- Classify: SECRET (never bake) / BUILD_ARG / RUNTIME
- Flag security issues
↓
3. FIX CONFIGURATION
- Add Next.js `output: 'standalone'` if missing
- Create health endpoints if missing
- Generate .env.example with safe placeholders
↓
4. GENERATE FILES
- Dockerfile (customized CMD, paths, build deps)
- .dockerignore (excludes .env, secrets)
- compose.yaml (with security defaults)
↓
5. VALIDATE & TEST
- docker build --target dev -t app:dev .
- docker build --target production -t app:prod .
- Test health endpoints
- Verify non-root user
- Report image size
↓
6. DELIVER WITH CONTEXT
- All files with explanations
- Security scan command
- Any warnings about secrets
- Rollback instructions if replacing existingOnly ask if genuinely ambiguous (e.g., multiple apps in monorepo, conflicting configs)
1. 扫描项目
- 检测运行时、框架、版本、入口点
- 查找依赖文件、原生依赖
- 定位现有Docker文件(不盲目覆盖)
↓
2. 分析环境
- 扫描所有.env*文件
- 分类:敏感信息(绝不嵌入)/ 构建参数 / 运行时配置
- 标记安全问题
↓
3. 修复配置
- 如果缺失则为Next.js添加`output: 'standalone'`
- 如果缺失则创建健康检查端点
- 生成包含安全占位符的.env.example
↓
4. 生成文件
- Dockerfile(定制化CMD、路径、构建依赖)
- .dockerignore(排除.env、敏感信息)
- compose.yaml(带有安全默认配置)
↓
5. 验证与测试
- docker build --target dev -t app:dev .
- docker build --target production -t app:prod .
- 测试健康检查端点
- 验证非root用户
- 报告镜像大小
↓
6. 附带上下文交付
- 所有文件及说明
- 安全扫描命令
- 关于敏感信息的警告
- 替换现有文件时的回滚说明仅当确实存在歧义时才询问(例如,单体仓库中有多个应用、配置冲突)
Base Image Decision Matrix
基础镜像决策矩阵
| Choice | When to Use | Tradeoffs |
|---|---|---|
Slim | General production (default) | Works everywhere, no auth |
DHI | SOC2/HIPAA, enterprise | Requires |
Alpine | Smallest size | musl issues with native deps |
Default: Slim (works everywhere without authentication)
| 选择 | 使用场景 | 权衡 |
|---|---|---|
Slim | 通用生产环境(默认) | 可在所有环境使用,无需认证 |
DHI | SOC2/HIPAA合规、企业环境 | 需要 |
Alpine | 最小镜像体积 | 原生依赖存在musl兼容性问题 |
默认选择:Slim(无需认证即可在所有环境使用)
Stage Structure
阶段结构
deps/base → Install dependencies (cached layer)
↓
builder → Build/compile application
↓
dev → Hot-reload, volume mounts (--target dev)
↓
production → Minimal DHI runtime (--target production)deps/base → 安装依赖(缓存层)
↓
builder → 构建/编译应用
↓
dev → 热重载、卷挂载(--target dev)
↓
production → 最小化DHI运行时(--target production)Build Commands
构建命令
bash
docker build --target dev -t myapp:dev .
docker build --target production -t myapp:prod .bash
docker build --target dev -t myapp:dev .
docker build --target production -t myapp:prod .Python Patterns
Python模式
Framework CMD
框架CMD命令
| Framework | Development | Production |
|---|---|---|
| FastAPI | | |
| Flask | | |
| Django | | |
| 框架 | 开发环境 | 生产环境 |
|---|---|---|
| FastAPI | | |
| Flask | | |
| Django | | |
Cache Mount (uv/pip)
缓存挂载(uv/pip)
dockerfile
RUN \
uv pip install -r requirements.txtdockerfile
RUN \
uv pip install -r requirements.txtGraceful Shutdown (FastAPI)
优雅关闭(FastAPI)
python
@asynccontextmanager
async def lifespan(app: FastAPI):
yield # startup
# shutdown logic herepython
@asynccontextmanager
async def lifespan(app: FastAPI):
yield # 启动
# 此处添加关闭逻辑Node.js Patterns
Node.js模式
Framework Build
框架构建
| Framework | Build | Output |
|---|---|---|
| Next.js | | |
| Express | | |
| NestJS | | |
| 框架 | 构建命令 | 输出目录 |
|---|---|---|
| Next.js | | |
| Express | | |
| NestJS | | |
Cache Mounts
缓存挂载
dockerfile
undefineddockerfile
undefinedpnpm
pnpm
RUN --mount=type=cache,target=/root/.local/share/pnpm/store
pnpm install --frozen-lockfile
pnpm install --frozen-lockfile
RUN --mount=type=cache,target=/root/.local/share/pnpm/store
pnpm install --frozen-lockfile
pnpm install --frozen-lockfile
npm
npm
RUN --mount=type=cache,target=/root/.npm npm ci
RUN --mount=type=cache,target=/root/.npm npm ci
yarn
yarn
RUN --mount=type=cache,target=/usr/local/share/.cache/yarn
yarn install --frozen-lockfile
yarn install --frozen-lockfile
undefinedRUN --mount=type=cache,target=/usr/local/share/.cache/yarn
yarn install --frozen-lockfile
yarn install --frozen-lockfile
undefinedGraceful Shutdown (Node.js)
优雅关闭(Node.js)
javascript
process.on('SIGTERM', () => {
server.close(() => process.exit(0));
});javascript
process.on('SIGTERM', () => {
server.close(() => process.exit(0));
});Security Checklist
安全检查清单
Before delivering, verify:
- Non-root USER in production stage
- No secrets in Dockerfile or image layers
- .dockerignore excludes ,
.env, secrets.git - Multi-stage separates build tools from runtime
- DHI or hardened base image used
- HEALTHCHECK instruction defined
- No package install in production stage
- Secrets via runtime env vars or mounted files
交付前,需验证以下内容:
- 生产阶段使用非root用户
- Dockerfile或镜像层中无敏感信息
- .dockerignore排除、
.env、敏感信息.git - 多阶段构建分离构建工具与运行时
- 使用DHI或加固基础镜像
- 定义了HEALTHCHECK指令
- 生产阶段不安装包
- 敏感信息通过运行时环境变量或挂载文件提供
Output Files
输出文件
| File | Purpose |
|---|---|
| Multi-stage, multi-target build |
| Exclude sensitive/unnecessary files |
| Local development stack |
| Framework-specific health checks |
| 文件 | 用途 |
|---|---|
| 多阶段、多目标构建文件 |
| 排除敏感/不必要文件 |
| 本地开发栈配置 |
| 框架专属健康检查 |
Reference Files
参考文件
Always Read First
优先阅读
| File | Purpose |
|---|---|
| CRITICAL: Secret detection, .env classification |
| CRITICAL: Validation before delivery |
| 文件 | 用途 |
|---|---|
| 关键:敏感信息检测、.env文件分类 |
| 关键:交付前验证清单 |
Framework-Specific
框架专属
| File | When to Read |
|---|---|
| FastAPI: uvicorn, lifespan |
| Flask: gunicorn, blueprints |
| Django: gunicorn, middleware |
| Detect psycopg2, cryptography, etc. |
| Next.js: standalone, ISR |
| npm/yarn/pnpm caching |
| 文件 | 阅读时机 |
|---|---|
| FastAPI:uvicorn、生命周期 |
| Flask:gunicorn、蓝图 |
| Django:gunicorn、中间件 |
| 检测psycopg2、cryptography等原生依赖 |
| Next.js:standalone、增量静态再生 |
| npm/yarn/pnpm缓存 |
Optional
可选
| File | When to Read |
|---|---|
| If user needs enterprise security (DHI) |
| Complex build patterns |
| 文件 | 阅读时机 |
|---|---|
| 如果用户需要企业级安全(DHI) |
| 复杂构建模式 |
Templates (Reference Patterns)
模板(参考模式)
Templates in are reference patterns, not copy-paste files.
templates/Agent must:
- Read template to understand structure
- Customize paths, CMDs, and stages for actual project
- Generate Dockerfile with correct entrypoint (e.g., )
src.app.main:app - Never output placeholder comments like "# Replace based on framework"
Example customization:
dockerfile
undefinedtemplates/Agent必须:
- 阅读模板以理解结构
- 根据实际项目定制路径、CMD命令和阶段
- 生成带有正确入口点的Dockerfile(例如:)
src.app.main:app - 绝不输出类似"# 根据框架替换"的占位符注释
定制示例:
dockerfile
undefinedTemplate says:
模板内容:
CMD ["uvicorn", "app.main:app", ...]
CMD ["uvicorn", "app.main:app", ...]
Agent detects app at src/api/main.py, generates:
Agent检测到应用位于src/api/main.py,生成:
CMD ["uvicorn", "src.api.main:app", ...]
undefinedCMD ["uvicorn", "src.api.main:app", ...]
undefined