docker-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Docker Development

Docker开发

Smaller images. Faster builds. Secure containers. No guesswork.
Opinionated Docker workflow that turns bloated Dockerfiles into production-grade containers. Covers optimization, multi-stage builds, compose orchestration, and security hardening.
Not a Docker tutorial — a set of concrete decisions about how to build containers that don't waste time, space, or attack surface.

更小的镜像、更快的构建、更安全的容器,无需猜测。
一套实用的Docker工作流,可将臃肿的Dockerfile转换为生产级容器。涵盖优化、多阶段构建、Compose编排以及安全加固。
这不是Docker教程——而是关于如何构建不浪费时间、空间或攻击面的容器的一系列具体决策。

Slash Commands

斜杠命令

CommandWhat it does
/docker:optimize
Analyze and optimize a Dockerfile for size, speed, and layer caching
/docker:compose
Generate or improve docker-compose.yml with best practices
/docker:security
Audit a Dockerfile or running container for security issues

命令功能
/docker:optimize
分析并优化Dockerfile的尺寸、构建速度和层缓存
/docker:compose
遵循最佳实践生成或改进docker-compose.yml
/docker:security
审计Dockerfile或运行中容器的安全问题

When This Skill Activates

技能触发场景

Recognize these patterns from the user:
  • "Optimize this Dockerfile"
  • "My Docker build is slow"
  • "Create a docker-compose for this project"
  • "Is this Dockerfile secure?"
  • "Reduce my Docker image size"
  • "Set up multi-stage builds"
  • "Docker best practices for [language/framework]"
  • Any request involving: Dockerfile, docker-compose, container, image size, build cache, Docker security
If the user has a Dockerfile or wants to containerize something → this skill applies.

识别用户的以下请求模式:
  • "优化这个Dockerfile"
  • "我的Docker构建速度很慢"
  • "为这个项目创建docker-compose配置"
  • "这个Dockerfile安全吗?"
  • "减小我的Docker镜像尺寸"
  • "设置多阶段构建"
  • "[语言/框架]的Docker最佳实践"
  • 任何涉及Dockerfile、docker-compose、容器、镜像尺寸、构建缓存、Docker安全的请求
如果用户拥有Dockerfile或希望将应用容器化 → 适用本技能。

Workflow

工作流

/docker:optimize
— Dockerfile Optimization

/docker:optimize
— Dockerfile优化

  1. Analyze current state
    • Read the Dockerfile
    • Identify base image and its size
    • Count layers (each RUN/COPY/ADD = 1 layer)
    • Check for common anti-patterns
  2. Apply optimization checklist
    BASE IMAGE
    ├── Use specific tags, never :latest in production
    ├── Prefer slim/alpine variants (debian-slim > ubuntu > debian)
    ├── Pin digest for reproducibility in CI: image@sha256:...
    └── Match base to runtime needs (don't use python:3.12 for a compiled binary)
    
    LAYER OPTIMIZATION
    ├── Combine related RUN commands with && \
    ├── Order layers: least-changing first (deps before source code)
    ├── Clean package manager cache in the same RUN layer
    ├── Use .dockerignore to exclude unnecessary files
    └── Separate build deps from runtime deps
    
    BUILD CACHE
    ├── COPY dependency files before source code (package.json, requirements.txt, go.mod)
    ├── Install deps in a separate layer from code copy
    ├── Use BuildKit cache mounts: --mount=type=cache,target=/root/.cache
    └── Avoid COPY . . before dependency installation
    
    MULTI-STAGE BUILDS
    ├── Stage 1: build (full SDK, build tools, dev deps)
    ├── Stage 2: runtime (minimal base, only production artifacts)
    ├── COPY --from=builder only what's needed
    └── Final image should have NO build tools, NO source code, NO dev deps
  3. Generate optimized Dockerfile
    • Apply all relevant optimizations
    • Add inline comments explaining each decision
    • Report estimated size reduction
  4. Validate
    bash
    python3 scripts/dockerfile_analyzer.py Dockerfile
  1. 分析当前状态
    • 读取Dockerfile
    • 识别基础镜像及其尺寸
    • 统计层数(每个RUN/COPY/ADD命令对应1层)
    • 检查常见反模式
  2. 应用优化检查清单
    BASE IMAGE
    ├── 生产环境使用特定标签,绝不使用:latest
    ├── 优先选择slim/alpine变体(debian-slim > ubuntu > debian)
    ├── CI环境中固定摘要以保证可复现性:image@sha256:...
    └── 根据运行时需求匹配基础镜像(不要为编译后的二进制文件使用python:3.12)
    
    LAYER OPTIMIZATION
    ├── 使用&& \合并相关RUN命令
    ├── 按变更频率排序层:变更最少的在前(依赖项优先于源代码)
    ├── 在同一个RUN层中清理包管理器缓存
    ├── 使用.dockerignore排除不必要的文件
    └── 将构建依赖与运行时依赖分离
    
    BUILD CACHE
    ├── 在复制源代码前先复制依赖文件(package.json、requirements.txt、go.mod)
    ├── 在独立层中安装依赖,与代码复制分离
    ├── 使用BuildKit缓存挂载:--mount=type=cache,target=/root/.cache
    └── 避免在依赖安装前执行COPY . .
    
    MULTI-STAGE BUILDS
    ├── 阶段1:构建(完整SDK、构建工具、开发依赖)
    ├── 阶段2:运行时(最小化基础镜像,仅包含生产工件)
    ├── 仅从builder阶段复制所需内容
    └── 最终镜像应无构建工具、无源代码、无开发依赖
  3. 生成优化后的Dockerfile
    • 应用所有相关优化
    • 添加内联注释解释每项决策
    • 报告预估的尺寸缩减量
  4. 验证
    bash
    python3 scripts/dockerfile_analyzer.py Dockerfile

/docker:compose
— Docker Compose Configuration

/docker:compose
— Docker Compose配置

  1. Identify services
    • Application (web, API, worker)
    • Database (postgres, mysql, redis, mongo)
    • Cache (redis, memcached)
    • Queue (rabbitmq, kafka)
    • Reverse proxy (nginx, traefik, caddy)
  2. Apply compose best practices
    SERVICES
    ├── Use depends_on with condition: service_healthy
    ├── Add healthchecks for every service
    ├── Set resource limits (mem_limit, cpus)
    ├── Use named volumes for persistent data
    └── Pin image versions
    
    NETWORKING
    ├── Create explicit networks (don't rely on default)
    ├── Separate frontend and backend networks
    ├── Only expose ports that need external access
    └── Use internal: true for backend-only networks
    
    ENVIRONMENT
    ├── Use env_file for secrets, not inline environment
    ├── Never commit .env files (add to .gitignore)
    ├── Use variable substitution: ${VAR:-default}
    └── Document all required env vars
    
    DEVELOPMENT vs PRODUCTION
    ├── Use compose profiles or override files
    ├── Dev: bind mounts for hot reload, debug ports exposed
    ├── Prod: named volumes, no debug ports, restart: unless-stopped
    └── docker-compose.override.yml for dev-only config
  3. Generate compose file
    • Output docker-compose.yml with healthchecks, networks, volumes
    • Generate .env.example with all required variables documented
    • Add dev/prod profile annotations
  1. 识别服务
    • 应用服务(web、API、worker)
    • 数据库(postgres、mysql、redis、mongo)
    • 缓存(redis、memcached)
    • 队列(rabbitmq、kafka)
    • 反向代理(nginx、traefik、caddy)
  2. 应用Compose最佳实践
    SERVICES
    ├── 使用depends_on并搭配condition: service_healthy
    ├── 为每个服务添加健康检查
    ├── 设置资源限制(mem_limit、cpus)
    ├── 使用命名卷存储持久化数据
    └── 固定镜像版本
    
    NETWORKING
    ├── 创建显式网络(不要依赖默认网络)
    ├── 分离前端和后端网络
    ├── 仅暴露需要外部访问的端口
    └── 为仅后端网络设置internal: true
    
    ENVIRONMENT
    ├── 使用env_file存储密钥,不要内联环境变量
    ├── 绝不提交.env文件(添加到.gitignore)
    ├── 使用变量替换:${VAR:-default}
    └── 记录所有必需的环境变量
    
    DEVELOPMENT vs PRODUCTION
    ├── 使用Compose配置文件或覆盖文件
    ├── 开发环境:绑定挂载实现热重载,暴露调试端口
    ├── 生产环境:使用命名卷,不暴露调试端口,设置restart: unless-stopped
    └── 使用docker-compose.override.yml存储仅开发环境的配置
  3. 生成Compose文件
    • 输出包含健康检查、网络、卷的docker-compose.yml
    • 生成包含所有必需变量说明的.env.example
    • 添加开发/生产环境配置文件注解

/docker:security
— Container Security Audit

/docker:security
— 容器安全审计

  1. Dockerfile audit
    CheckSeverityFix
    Running as rootCriticalAdd
    USER nonroot
    after creating user
    Using :latest tagHighPin to specific version
    Secrets in ENV/ARGCriticalUse BuildKit secrets:
    --mount=type=secret
    COPY with broad globMediumUse specific paths, add .dockerignore
    Unnecessary EXPOSELowOnly expose ports the app uses
    No HEALTHCHECKMediumAdd HEALTHCHECK with appropriate interval
    Privileged instructionsHighAvoid
    --privileged
    , drop capabilities
    Package manager cache retainedLowClean in same RUN layer
  2. Runtime security checks
    CheckSeverityFix
    Container running as rootCriticalSet user in Dockerfile or compose
    Writable root filesystemMediumUse
    read_only: true
    in compose
    All capabilities retainedHighDrop all, add only needed:
    cap_drop: [ALL]
    No resource limitsMediumSet
    mem_limit
    and
    cpus
    Host network modeHighUse bridge or custom network
    Sensitive mountsCriticalNever mount /etc, /var/run/docker.sock in prod
    No log driver configuredLowSet
    logging:
    with size limits
  3. Generate security report
    SECURITY AUDIT — [Dockerfile/Image name]
    Date: [timestamp]
    
    CRITICAL: [count]
    HIGH:     [count]
    MEDIUM:   [count]
    LOW:      [count]
    
    [Detailed findings with fix recommendations]

  1. Dockerfile审计
    检查项严重程度修复方案
    以root用户运行严重创建用户后添加
    USER nonroot
    使用:latest标签固定到特定版本
    密钥存储在ENV/ARG中严重使用BuildKit密钥挂载:
    --mount=type=secret
    使用宽泛通配符COPY使用特定路径,添加.dockerignore
    不必要的EXPOSE仅暴露应用使用的端口
    无HEALTHCHECK添加合适间隔的HEALTHCHECK
    特权指令避免
    --privileged
    ,移除不必要的权限
    保留包管理器缓存在同一个RUN层中清理缓存
  2. 运行时安全检查
    检查项严重程度修复方案
    容器以root用户运行严重在Dockerfile或Compose中设置用户
    根文件系统可写在Compose中设置
    read_only: true
    保留所有权限移除所有权限,仅添加必需的:
    cap_drop: [ALL]
    无资源限制设置
    mem_limit
    cpus
    使用主机网络模式使用桥接或自定义网络
    敏感挂载严重生产环境绝不挂载/etc、/var/run/docker.sock
    未配置日志驱动设置带大小限制的
    logging:
  3. 生成安全报告
    安全审计 — [Dockerfile/镜像名称]
    日期: [时间戳]
    
    严重: [数量]
    高:     [数量]
    中:     [数量]
    低:      [数量]
    
    [带有修复建议的详细发现]

Tooling

工具集

scripts/dockerfile_analyzer.py

scripts/dockerfile_analyzer.py

CLI utility for static analysis of Dockerfiles.
Features:
  • Layer count and optimization suggestions
  • Base image analysis with size estimates
  • Anti-pattern detection (15+ rules)
  • Security issue flagging
  • Multi-stage build detection and validation
  • JSON and text output
Usage:
bash
undefined
用于Dockerfile静态分析的CLI工具。
特性:
  • 层数统计和优化建议
  • 基础镜像分析及尺寸预估
  • 反模式检测(15+规则)
  • 安全问题标记
  • 多阶段构建检测与验证
  • JSON和文本输出
使用方法:
bash
undefined

Analyze a Dockerfile

分析Dockerfile

python3 scripts/dockerfile_analyzer.py Dockerfile
python3 scripts/dockerfile_analyzer.py Dockerfile

JSON output

JSON输出

python3 scripts/dockerfile_analyzer.py Dockerfile --output json
python3 scripts/dockerfile_analyzer.py Dockerfile --output json

Analyze with security focus

聚焦安全分析

python3 scripts/dockerfile_analyzer.py Dockerfile --security
python3 scripts/dockerfile_analyzer.py Dockerfile --security

Check a specific directory

检查指定目录

python3 scripts/dockerfile_analyzer.py path/to/Dockerfile
undefined
python3 scripts/dockerfile_analyzer.py path/to/Dockerfile
undefined

scripts/compose_validator.py

scripts/compose_validator.py

CLI utility for validating docker-compose files.
Features:
  • Service dependency validation
  • Healthcheck presence detection
  • Network configuration analysis
  • Volume mount validation
  • Environment variable audit
  • Port conflict detection
  • Best practice scoring
Usage:
bash
undefined
用于验证docker-compose文件的CLI工具。
特性:
  • 服务依赖验证
  • 健康检查存在性检测
  • 网络配置分析
  • 卷挂载验证
  • 环境变量审计
  • 端口冲突检测
  • 最佳实践评分
使用方法:
bash
undefined

Validate a compose file

验证Compose文件

python3 scripts/compose_validator.py docker-compose.yml
python3 scripts/compose_validator.py docker-compose.yml

JSON output

JSON输出

python3 scripts/compose_validator.py docker-compose.yml --output json
python3 scripts/compose_validator.py docker-compose.yml --output json

Strict mode (fail on warnings)

严格模式(警告即失败)

python3 scripts/compose_validator.py docker-compose.yml --strict

---
python3 scripts/compose_validator.py docker-compose.yml --strict

---

Multi-Stage Build Patterns

多阶段构建模式

Pattern 1: Compiled Language (Go, Rust, C++)

模式1:编译型语言(Go、Rust、C++)

dockerfile
undefined
dockerfile
undefined

Build stage

Build stage

FROM golang:1.22-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /app/server ./cmd/server
FROM golang:1.22-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /app/server ./cmd/server

Runtime stage

Runtime stage

FROM gcr.io/distroless/static-debian12 COPY --from=builder /app/server /server USER nonroot:nonroot ENTRYPOINT ["/server"]
undefined
FROM gcr.io/distroless/static-debian12 COPY --from=builder /app/server /server USER nonroot:nonroot ENTRYPOINT ["/server"]
undefined

Pattern 2: Node.js / TypeScript

模式2:Node.js / TypeScript

dockerfile
undefined
dockerfile
undefined

Dependencies stage

Dependencies stage

FROM node:20-alpine AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --production=false
FROM node:20-alpine AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --production=false

Build stage

Build stage

FROM deps AS builder COPY . . RUN npm run build
FROM deps AS builder COPY . . RUN npm run build

Runtime stage

Runtime stage

FROM node:20-alpine WORKDIR /app RUN addgroup -g 1001 -S appgroup && adduser -S appuser -u 1001 COPY --from=builder /app/dist ./dist COPY --from=deps /app/node_modules ./node_modules COPY package.json ./ USER appuser EXPOSE 3000 CMD ["node", "dist/index.js"]
undefined
FROM node:20-alpine WORKDIR /app RUN addgroup -g 1001 -S appgroup && adduser -S appuser -u 1001 COPY --from=builder /app/dist ./dist COPY --from=deps /app/node_modules ./node_modules COPY package.json ./ USER appuser EXPOSE 3000 CMD ["node", "dist/index.js"]
undefined

Pattern 3: Python

模式3:Python

dockerfile
undefined
dockerfile
undefined

Build stage

Build stage

FROM python:3.12-slim AS builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
FROM python:3.12-slim AS builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

Runtime stage

Runtime stage

FROM python:3.12-slim WORKDIR /app RUN groupadd -r appgroup && useradd -r -g appgroup appuser COPY --from=builder /install /usr/local COPY . . USER appuser EXPOSE 8000 CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

---
FROM python:3.12-slim WORKDIR /app RUN groupadd -r appgroup && useradd -r -g appgroup appuser COPY --from=builder /install /usr/local COPY . . USER appuser EXPOSE 8000 CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

---

Base Image Decision Tree

基础镜像决策树

Is it a compiled binary (Go, Rust, C)?
├── Yes → distroless/static or scratch
└── No
    ├── Need a shell for debugging?
    │   ├── Yes → alpine variant (e.g., node:20-alpine)
    │   └── No → distroless variant
    ├── Need glibc (not musl)?
    │   ├── Yes → slim variant (e.g., python:3.12-slim)
    │   └── No → alpine variant
    └── Need specific OS packages?
        ├── Many → debian-slim
        └── Few → alpine + apk add

是否为编译后的二进制文件(Go、Rust、C)?
├── 是 → 使用distroless/static或scratch
└── 否
    ├── 需要shell用于调试?
    │   ├── 是 → 使用alpine变体(如node:20-alpine)
    │   └── 否 → 使用distroless变体
    ├── 需要glibc(而非musl)?
    │   ├── 是 → 使用slim变体(如python:3.12-slim)
    │   └── 否 → 使用alpine变体
    └── 需要特定OS包?
        ├── 多个 → 使用debian-slim
        └── 少量 → 使用alpine + apk add

Proactive Triggers

主动触发提示

Flag these without being asked:
  • Dockerfile uses :latest → Suggest pinning to a specific version tag.
  • No .dockerignore → Create one. At minimum:
    .git
    ,
    node_modules
    ,
    __pycache__
    ,
    .env
    .
  • COPY . . before dependency install → Cache bust. Reorder to install deps first.
  • Running as root → Add USER instruction. No exceptions for production.
  • Secrets in ENV or ARG → Use BuildKit secret mounts. Never bake secrets into layers.
  • Image over 1GB → Multi-stage build required. No reason for a production image this large.
  • No healthcheck → Add one. Orchestrators (Compose, K8s) need it for proper lifecycle management.
  • apt-get without cleanup in same layer
    rm -rf /var/lib/apt/lists/*
    in the same RUN.

无需用户询问,自动标记以下问题:
  • Dockerfile使用:latest → 建议固定到特定版本标签。
  • 无.dockerignore → 创建该文件。至少包含:
    .git
    node_modules
    __pycache__
    .env
  • 在依赖安装前执行COPY . . → 缓存失效。调整顺序为先安装依赖。
  • 以root用户运行 → 添加USER指令。生产环境无例外。
  • 密钥存储在ENV或ARG中 → 使用BuildKit密钥挂载。绝不要将密钥 baked 到镜像层中。
  • 镜像超过1GB → 需要多阶段构建。生产镜像没有理由这么大。
  • 无健康检查 → 添加健康检查。编排工具(Compose、K8s)需要它进行正确的生命周期管理。
  • apt-get未在同一层清理缓存 → 在同一个RUN命令中添加
    rm -rf /var/lib/apt/lists/*

Installation

安装方法

One-liner (any tool)

一键安装(适用于所有工具)

bash
git clone https://github.com/alirezarezvani/claude-skills.git
cp -r claude-skills/engineering/docker-development ~/.claude/skills/
bash
git clone https://github.com/alirezarezvani/claude-skills.git
cp -r claude-skills/engineering/docker-development ~/.claude/skills/

Multi-tool install

多工具适配安装

bash
./scripts/convert.sh --skill docker-development --tool codex|gemini|cursor|windsurf|openclaw
bash
./scripts/convert.sh --skill docker-development --tool codex|gemini|cursor|windsurf|openclaw

OpenClaw

OpenClaw

bash
clawhub install cs-docker-development

bash
clawhub install cs-docker-development

Related Skills

相关技能

  • senior-devops — Broader DevOps scope (CI/CD, IaC, monitoring). Complementary — use docker-development for container-specific work, senior-devops for pipeline and infrastructure.
  • senior-security — Application security. Complementary — docker-development covers container security, senior-security covers application-level threats.
  • autoresearch-agent — Can optimize Docker build times or image sizes as measurable experiments.
  • ci-cd-pipeline-builder — Pipeline construction. Complementary — docker-development builds the containers, ci-cd-pipeline-builder deploys them.
  • senior-devops — 更广泛的DevOps范围(CI/CD、IaC、监控)。互补技能——容器相关工作使用docker-development,流水线和基础设施工作使用senior-devops。
  • senior-security — 应用安全。互补技能——docker-development覆盖容器安全,senior-security覆盖应用级威胁。
  • autoresearch-agent — 可将Docker构建时间或镜像尺寸优化作为可衡量的实验。
  • ci-cd-pipeline-builder — 流水线构建。互补技能——docker-development构建容器,ci-cd-pipeline-builder负责部署。