docker

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Docker

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
undefined

Detect 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"}'
sysctl -n hw.memsize 2>/dev/null | awk '{print $0/1024/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行为

  1. Detect Docker resources before generating compose.yaml
  2. Adapt resource limits to available memory
  3. Warn if build may fail due to insufficient resources
  4. Calculate safe limits:
    docker_memory * 0.6 / container_count
  1. 检测:生成compose.yaml之前先检测Docker资源
  2. 适配:根据可用内存调整资源限制
  3. 警告:如果资源不足可能导致构建失败,发出警告
  4. 计算:安全限制公式:
    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: 256M
Extended (> 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: 512M

Pre-Build Validation

构建前验证

Before running
docker build
, agent should verify:
bash
undefined
运行
docker build
之前,Agent应执行以下验证:
bash
undefined

Check 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
    output: 'standalone'
    to Next.js, etc.)
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:
SourceGather
CodebasePackage files, existing Dockerfile, .env patterns
ConversationDev vs production target, base image preferences
Skill ReferencesFramework patterns, multi-stage builds, security
User GuidelinesRegistry conventions, naming standards

收集上下文信息以确保实施成功:
来源收集内容
代码库包文件、现有Dockerfile、.env文件模式
对话记录开发或生产目标、基础镜像偏好
技能参考框架模式、多阶段构建、安全规范
用户指南镜像仓库约定、命名标准

Required Clarifications

需要确认的信息

Ask when not auto-detectable:
QuestionWhen 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 PresentRuntimePackage Manager
requirements.txt
,
pyproject.toml
,
uv.lock
Pythonpip/uv
pnpm-lock.yaml
Node.jspnpm
yarn.lock
Node.jsyarn
package-lock.json
Node.jsnpm

存在的文件运行时包管理器
requirements.txt
,
pyproject.toml
,
uv.lock
Pythonpip/uv
pnpm-lock.yaml
Node.jspnpm
yarn.lock
Node.jsyarn
package-lock.json
Node.jsnpm

Auto-Detection (Do NOT ask - detect from files)

自动检测(无需询问 - 从文件中检测)

Python

Python

WhatDetect From
Python version
pyproject.toml
(requires-python),
.python-version
,
runtime.txt
FrameworkImports in code (
from fastapi
,
from flask
,
import django
)
Package manager
uv.lock
→ uv,
poetry.lock
→ poetry, else pip
Native depsScan requirements:
psycopg2
,
cryptography
,
numpy
,
pillow
App entrypointFind
app = FastAPI()
,
app = Flask()
, or
manage.py
检测内容检测来源
Python版本
pyproject.toml
(requires-python字段)、
.python-version
runtime.txt
框架代码中的导入语句(
from fastapi
from flask
import django
包管理器
uv.lock
→ uv,
poetry.lock
→ poetry,否则为pip
原生依赖扫描requirements文件:
psycopg2
cryptography
numpy
pillow
应用入口点查找
app = FastAPI()
app = Flask()
manage.py

Node.js

Node.js

WhatDetect From
Node version
.nvmrc
,
.node-version
,
package.json
(engines.node)
Framework
package.json
dependencies (next, express, @nestjs/core)
Package manager
pnpm-lock.yaml
→ pnpm,
yarn.lock
→ yarn, else npm
Output typeNext.js: check
next.config.js
for
output: 'standalone'
检测内容检测来源
Node版本
.nvmrc
.node-version
package.json
(engines.node字段)
框架
package.json
中的依赖(next、express、@nestjs/core)
包管理器
pnpm-lock.yaml
→ pnpm,
yarn.lock
→ yarn,否则为npm
输出类型Next.js:检查
next.config.js
中是否有
output: 'standalone'

Fix Issues Automatically

自动修复问题

IssueAction
Next.js missing
output: 'standalone'
Add it to next.config.js
No health endpoint foundCreate
/health/live
and
/health/ready
Using uv but no uv.lockRun
uv lock
first
pyproject.toml but no build systemUse
uv pip install -r pyproject.toml

问题操作
Next.js缺失
output: 'standalone'
添加到next.config.js
未找到健康检查端点创建
/health/live
/health/ready
使用uv但无uv.lock先运行
uv lock
存在pyproject.toml但无构建系统使用
uv pip install -r 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 existing
Only 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

基础镜像决策矩阵

ChoiceWhen to UseTradeoffs
Slim
{runtime}:X-slim
General production (default)Works everywhere, no auth
DHI
dhi.io/{runtime}:X
SOC2/HIPAA, enterpriseRequires
docker login dhi.io
Alpine
{runtime}:X-alpine
Smallest sizemusl issues with native deps
Default: Slim (works everywhere without authentication)

选择使用场景权衡
Slim
{runtime}:X-slim
通用生产环境(默认)可在所有环境使用,无需认证
DHI
dhi.io/{runtime}:X
SOC2/HIPAA合规、企业环境需要
docker login dhi.io
Alpine
{runtime}:X-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命令

FrameworkDevelopmentProduction
FastAPI
uvicorn app.main:app --reload
uvicorn app.main:app --workers 4
Flask
flask run --debug
gunicorn -w 4 app:app
Django
python manage.py runserver
gunicorn -w 4 project.wsgi
框架开发环境生产环境
FastAPI
uvicorn app.main:app --reload
uvicorn app.main:app --workers 4
Flask
flask run --debug
gunicorn -w 4 app:app
Django
python manage.py runserver
gunicorn -w 4 project.wsgi

Cache Mount (uv/pip)

缓存挂载(uv/pip)

dockerfile
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=cache,target=/root/.cache/pip \
    uv pip install -r requirements.txt
dockerfile
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=cache,target=/root/.cache/pip \
    uv pip install -r requirements.txt

Graceful Shutdown (FastAPI)

优雅关闭(FastAPI)

python
@asynccontextmanager
async def lifespan(app: FastAPI):
    yield  # startup
    # shutdown logic here

python
@asynccontextmanager
async def lifespan(app: FastAPI):
    yield  # 启动
    # 此处添加关闭逻辑

Node.js Patterns

Node.js模式

Framework Build

框架构建

FrameworkBuildOutput
Next.js
next build
.next/standalone
Express
tsc
dist/
NestJS
nest build
dist/
框架构建命令输出目录
Next.js
next build
.next/standalone
Express
tsc
dist/
NestJS
nest build
dist/

Cache Mounts

缓存挂载

dockerfile
undefined
dockerfile
undefined

pnpm

pnpm

RUN --mount=type=cache,target=/root/.local/share/pnpm/store
pnpm install --frozen-lockfile
RUN --mount=type=cache,target=/root/.local/share/pnpm/store
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
undefined
RUN --mount=type=cache,target=/usr/local/share/.cache/yarn
yarn install --frozen-lockfile
undefined

Graceful 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
    ,
    .git
    , secrets
  • 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

输出文件

FilePurpose
Dockerfile
Multi-stage, multi-target build
.dockerignore
Exclude sensitive/unnecessary files
compose.yaml
Local development stack
health.py
/ health endpoint
Framework-specific health checks

文件用途
Dockerfile
多阶段、多目标构建文件
.dockerignore
排除敏感/不必要文件
compose.yaml
本地开发栈配置
health.py
/ 健康检查端点
框架专属健康检查

Reference Files

参考文件

Always Read First

优先阅读

FilePurpose
references/env-analysis.md
CRITICAL: Secret detection, .env classification
references/production-checklist.md
CRITICAL: Validation before delivery
文件用途
references/env-analysis.md
关键:敏感信息检测、.env文件分类
references/production-checklist.md
关键:交付前验证清单

Framework-Specific

框架专属

FileWhen to Read
references/python/fastapi.md
FastAPI: uvicorn, lifespan
references/python/flask.md
Flask: gunicorn, blueprints
references/python/django.md
Django: gunicorn, middleware
references/python/native-deps.md
Detect psycopg2, cryptography, etc.
references/node/nextjs.md
Next.js: standalone, ISR
references/node/package-managers.md
npm/yarn/pnpm caching
文件阅读时机
references/python/fastapi.md
FastAPI:uvicorn、生命周期
references/python/flask.md
Flask:gunicorn、蓝图
references/python/django.md
Django:gunicorn、中间件
references/python/native-deps.md
检测psycopg2、cryptography等原生依赖
references/node/nextjs.md
Next.js:standalone、增量静态再生
references/node/package-managers.md
npm/yarn/pnpm缓存

Optional

可选

FileWhen to Read
references/docker-hardened-images.md
If user needs enterprise security (DHI)
references/multi-stage-builds.md
Complex build patterns
文件阅读时机
references/docker-hardened-images.md
如果用户需要企业级安全(DHI)
references/multi-stage-builds.md
复杂构建模式

Templates (Reference Patterns)

模板(参考模式)

Templates in
templates/
are reference patterns, not copy-paste files.
Agent must:
  1. Read template to understand structure
  2. Customize paths, CMDs, and stages for actual project
  3. Generate Dockerfile with correct entrypoint (e.g.,
    src.app.main:app
    )
  4. Never output placeholder comments like "# Replace based on framework"
Example customization:
dockerfile
undefined
templates/
目录下的模板是参考模式,而非直接复制的文件。
Agent必须:
  1. 阅读模板以理解结构
  2. 根据实际项目定制路径、CMD命令和阶段
  3. 生成带有正确入口点的Dockerfile(例如:
    src.app.main:app
  4. 绝不输出类似"# 根据框架替换"的占位符注释
定制示例:
dockerfile
undefined

Template 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", ...]
undefined
CMD ["uvicorn", "src.api.main:app", ...]
undefined