container-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Container Development

容器开发

Expert knowledge for containerization and orchestration with focus on security-first, lean container images and 12-factor app methodology.
专注于安全优先、轻量容器镜像和12-factor应用方法论的容器化与编排专业知识。

Security Philosophy (Non-Negotiable)

安全理念(不可妥协)

Non-Root is MANDATORY: ALL production containers MUST run as non-root users. This is not optional.
Minimal Base Images: Use Alpine (~5MB) for Node.js/Go/Rust. Use slim (~50MB) for Python (musl compatibility issues with Alpine).
Multi-Stage Builds Required: Separate build and runtime environments. Build tools should NOT be in production images.
必须使用非Root用户:所有生产环境容器必须以非root用户运行,这是硬性要求。
轻量基础镜像:Node.js/Go/Rust使用Alpine(约5MB);Python使用slim(约50MB,Alpine存在musl兼容性问题)。
必须使用多阶段构建:分离构建与运行环境,构建工具不得出现在生产镜像中。

Core Expertise

核心专业能力

Container Image Construction
  • Dockerfile/Containerfile Authoring: Clear, efficient, and maintainable container build instructions
  • Multi-Stage Builds: Creating minimal, production-ready images
  • Image Optimization: Reducing image size, minimizing layer count, optimizing build cache
  • Security Hardening: Non-root users, minimal base images, vulnerability scanning
Container Orchestration
  • Service Architecture: Microservices with proper service discovery
  • Resource Management: CPU/memory limits, auto-scaling policies, resource quotas
  • Health & Monitoring: Health checks, readiness probes, observability patterns
  • Configuration Management: Environment variables, secrets, configuration management
容器镜像构建
  • Dockerfile/Containerfile编写:清晰、高效且可维护的容器构建指令
  • 多阶段构建:创建轻量的生产就绪镜像
  • 镜像优化:减小镜像体积、减少镜像层数、优化构建缓存
  • 安全加固:非root用户、轻量基础镜像、漏洞扫描
容器编排
  • 服务架构:具备服务发现能力的微服务架构
  • 资源管理:CPU/内存限制、自动扩缩容策略、资源配额
  • 健康与监控:健康检查、就绪探针、可观测性模式
  • 配置管理:环境变量、密钥、配置管理

Key Capabilities

关键功能

  • 12-Factor Adherence: Ensures containerized applications follow 12-factor principles, especially configuration and statelessness
  • Health & Reliability: Implements proper health checks, readiness probes, and restart policies
  • Skaffold Workflows: Structures containerized applications for efficient development loops
  • Orchestration Patterns: Designs service meshes, load balancing, and container communication
  • Performance Tuning: Optimizes container resource usage, startup times, and runtime performance
  • 遵循12-factor原则:确保容器化应用符合12-factor原则,尤其是配置与无状态化要求
  • 健康与可靠性:实现完善的健康检查、就绪探针与重启策略
  • Skaffold工作流:为容器化应用搭建高效的开发循环
  • 编排模式:设计服务网格、负载均衡与容器通信机制
  • 性能调优:优化容器资源占用、启动时间与运行时性能

Image Crafting Process

镜像制作流程

  1. Analyze: Understand application dependencies and build process
  2. Structure: Design multi-stage Dockerfile, separating build-time from runtime needs
  3. Ignore: Create comprehensive
    .dockerignore
    file
  4. Build & Scan: Build image and scan for vulnerabilities
  5. Refine: Iterate to optimize layer caching, reduce size, address security
  6. Validate: Ensure image runs correctly and adheres to 12-factor principles
  1. 分析:梳理应用依赖与构建流程
  2. 架构设计:设计多阶段Dockerfile,分离构建时与运行时需求
  3. 忽略配置:创建全面的
    .dockerignore
    文件
  4. 构建与扫描:构建镜像并进行漏洞扫描
  5. 优化迭代:迭代优化镜像缓存、减小体积、修复安全问题
  6. 验证:确保镜像正常运行且符合12-factor原则

Best Practices

最佳实践

Core Optimization Principles

核心优化原则

1. Multi-Stage Builds (MANDATORY):
  • Separate build-time dependencies from runtime
  • Keep build tools out of production images
  • Typical reduction: 60-90% smaller final images
2. Minimal Base Images:
  • Start with the smallest base that works
  • Prefer Alpine for most languages (except Python)
  • Consider distroless for maximum security
3. Non-Root Users (MANDATORY):
  • Always create and use non-root user
  • Set UID/GID explicitly (e.g., 1001)
  • Security compliance requirement
4. .dockerignore (MANDATORY):
  • Exclude
    .git
    ,
    node_modules
    ,
    __pycache__
  • Prevent secrets and dev files from entering image
  • Reduces build context by 90-98%
5. Layer Optimization:
  • Copy dependency manifests separately from source
  • Put frequently changing layers last
  • Combine related RUN commands with
    &&
1. 多阶段构建(必须):
  • 分离构建时依赖与运行时依赖
  • 禁止构建工具进入生产镜像
  • 典型效果:最终镜像体积减小60-90%
2. 轻量基础镜像
  • 选择满足需求的最小基础镜像
  • 多数语言优先使用Alpine(Python除外)
  • 追求极致安全可选择distroless镜像
3. 非Root用户(必须):
  • 始终创建并使用非root用户
  • 显式设置UID/GID(例如1001)
  • 合规性要求
4. .dockerignore(必须):
  • 排除
    .git
    node_modules
    __pycache__
  • 防止密钥与开发文件进入镜像
  • 构建上下文体积减少90-98%
5. 镜像层优化
  • 先复制依赖清单,再复制源代码(提升缓存效率)
  • 频繁变更的镜像层放在最后
  • 使用
    &&
    合并相关RUN命令

Version Checking

版本检查

CRITICAL: Before using base images, verify latest versions:
Use WebSearch or WebFetch to verify current versions.
关键:使用基础镜像前,务必验证最新版本:
使用WebSearch或WebFetch验证当前版本。

Language-Specific Optimization

语言专属优化

For detailed language-specific optimization patterns, see the dedicated skills:
LanguageSkillKey OptimizationTypical Reduction
Go
go-containers
Static binaries, scratch/distroless846MB → 2.5MB (99.7%)
Node.js
nodejs-containers
Alpine, multi-stage, npm/yarn/pnpm900MB → 100MB (89%)
Python
python-containers
Slim (NOT Alpine), uv, venv1GB → 100MB (90%)
关于各语言的详细优化模式,请参考专属技能:
语言Skill核心优化点典型压缩比例
Go
go-containers
Static binaries, scratch/distroless846MB → 2.5MB (99.7%)
Node.js
nodejs-containers
Alpine, multi-stage, npm/yarn/pnpm900MB → 100MB (89%)
Python
python-containers
Slim (NOT Alpine), uv, venv1GB → 100MB (90%)

Quick Base Image Guide

快速基础镜像指南

Choose the right base image:
  • Go:
    scratch
    or
    distroless/static
    (2-5MB)
  • Node.js:
    node:XX-alpine
    (50-150MB)
  • Python:
    python:XX-slim
    (80-120MB) - Never use Alpine for Python!
  • Nginx:
    nginx:XX-alpine
    (20-40MB)
  • Static files:
    scratch
    or
    nginx:alpine
    (minimal)
选择合适的基础镜像
  • Go
    scratch
    distroless/static
    (2-5MB)
  • Node.js
    node:XX-alpine
    (50-150MB)
  • Python
    python:XX-slim
    (80-120MB)- Python绝对不要用Alpine!
  • Nginx
    nginx:XX-alpine
    (20-40MB)
  • 静态文件
    scratch
    nginx:alpine
    (极致轻量)

Multi-Stage Build Template

多阶段构建模板

dockerfile
undefined
dockerfile
undefined

Build stage - includes all build tools

Build stage - includes all build tools

FROM <language>:<version> AS builder WORKDIR /app
FROM <language>:<version> AS builder WORKDIR /app

Copy dependency manifests first (better caching)

Copy dependency manifests first (better caching)

COPY package.json package-lock.json ./ # or go.mod, requirements.txt, etc.
COPY package.json package-lock.json ./ # or go.mod, requirements.txt, etc.

Install dependencies

Install dependencies

RUN <install-command>
RUN <install-command>

Copy source code

Copy source code

COPY . .
COPY . .

Build application

Build application

RUN <build-command>
RUN <build-command>

Runtime stage - minimal

Runtime stage - minimal

FROM <minimal-base> WORKDIR /app
FROM <minimal-base> WORKDIR /app

Create non-root user

Create non-root user

RUN addgroup --gid 1001 appgroup &&
adduser --uid 1001 --gid 1001 --disabled-password appuser
RUN addgroup --gid 1001 appgroup &&
adduser --uid 1001 --gid 1001 --disabled-password appuser

Copy only what's needed from builder

Copy only what's needed from builder

COPY --from=builder --chown=appuser:appuser /app/dist ./dist
USER appuser EXPOSE <port>
HEALTHCHECK --interval=30s CMD <health-check-command>
CMD [<start-command>]

**Security Requirements (Mandatory)**
- **Non-root user**: REQUIRED - never run as root in production
- **Minimal base images**: Choose smallest viable base
  - Typical CVE reduction: 50-100% (full base: 50-70 CVEs → minimal: 0-12 CVEs)
  - No shell = no shell injection attacks
  - No package manager = no supply chain attacks
- **Multi-stage builds**: REQUIRED - keep build tools out of runtime
- **HEALTHCHECK**: REQUIRED for Kubernetes liveness/readiness probes
- **Vulnerability scanning**: Use Trivy, Grype, or Docker Scout in CI
- **Version pinning**: Always use specific tags (e.g., `node:20.10-alpine`), never `latest`
- **.dockerignore**: REQUIRED - prevents secrets, .env, .git from entering image

**Typical Impact of Full Optimization**:
- **Image size**: 85-99% reduction
- **Security**: 70-100% fewer CVEs
- **Pull time**: 80-98% faster
- **Build time**: 40-60% faster (with proper caching)
- **Memory usage**: 60-80% lower
- **Storage costs**: 90-99% reduction

**12-Factor App Principles**
- Configuration via environment variables
- Stateless processes
- Explicit dependencies
- Port binding for services
- Graceful shutdown handling
COPY --from=builder --chown=appuser:appuser /app/dist ./dist
USER appuser EXPOSE <port>
HEALTHCHECK --interval=30s CMD <health-check-command>
CMD [<start-command>]

**安全要求(必须)**
- **非Root用户**:生产环境禁止以root用户运行
- **轻量基础镜像**:选择满足需求的最小镜像
  - 典型效果:CVE漏洞数量减少50-100%(完整基础镜像:50-70个CVE → 轻量镜像:0-12个CVE)
  - 无Shell = 避免Shell注入攻击
  - 无包管理器 = 避免供应链攻击
- **多阶段构建**:必须将构建工具排除在运行时镜像外
- **HEALTHCHECK**:为Kubernetes存活/就绪探针提供支持
- **漏洞扫描**:在CI中使用Trivy、Grype或Docker Scout
- **版本固定**:始终使用具体标签(例如`node:20.10-alpine`),绝对不要用`latest`
- **.dockerignore**:必须配置,防止密钥、.env、.git文件进入镜像

**全面优化的典型收益**:
- **镜像体积**:减少85-99%
- **安全性**:CVE漏洞减少70-100%
- **拉取时间**:加快80-98%
- **构建时间**:加快40-60%(配合合理缓存)
- **内存占用**:降低60-80%
- **存储成本**:减少90-99%

**12-factor应用原则**
- 通过环境变量管理配置
- 无状态进程
- 显式声明依赖
- 服务通过端口绑定提供
- 优雅处理关闭请求

Container Labels (OCI Annotations)

容器标签(OCI注解)

Container labels provide metadata for image discovery, linking, and documentation. GitHub Container Registry (GHCR) specifically supports OCI annotations to link images to repositories and display descriptions.
容器标签用于提供镜像的元数据,支持镜像发现、关联与文档记录。GitHub Container Registry (GHCR) 原生支持OCI注解,可将镜像关联到代码仓库并展示描述信息。

Required Labels for GHCR

GHCR必填标签

LabelPurposeExample
org.opencontainers.image.source
Links image to repository (enables GHCR features)
https://github.com/owner/repo
org.opencontainers.image.description
Package description (max 512 chars)
Production API server
org.opencontainers.image.licenses
SPDX license identifier (max 256 chars)
MIT
,
Apache-2.0
标签用途示例
org.opencontainers.image.source
关联镜像到代码仓库(启用GHCR专属功能)
https://github.com/owner/repo
org.opencontainers.image.description
包描述(最多512字符)
Production API server
org.opencontainers.image.licenses
SPDX许可证标识(最多256字符)
MIT
,
Apache-2.0

Recommended Labels

推荐标签

LabelPurposeExample
org.opencontainers.image.version
Semantic version
1.2.3
org.opencontainers.image.revision
Git commit SHA
abc1234
org.opencontainers.image.created
Build timestamp (RFC 3339)
2025-01-19T12:00:00Z
org.opencontainers.image.title
Human-readable name
My Application
org.opencontainers.image.vendor
Organization name
Forum Virium Helsinki
org.opencontainers.image.url
Project homepage
https://example.com
org.opencontainers.image.documentation
Documentation URL
https://docs.example.com
标签用途示例
org.opencontainers.image.version
语义化版本
1.2.3
org.opencontainers.image.revision
Git提交SHA
abc1234
org.opencontainers.image.created
构建时间戳(RFC 3339格式)
2025-01-19T12:00:00Z
org.opencontainers.image.title
人类可读名称
My Application
org.opencontainers.image.vendor
组织名称
Forum Virium Helsinki
org.opencontainers.image.url
项目主页
https://example.com
org.opencontainers.image.documentation
文档地址
https://docs.example.com

Adding Labels in Dockerfile

在Dockerfile中添加标签

dockerfile
undefined
dockerfile
undefined

Static labels (set at build time)

Static labels (set at build time)

LABEL org.opencontainers.image.source="https://github.com/owner/repo"
org.opencontainers.image.description="Production API server"
org.opencontainers.image.licenses="MIT"
org.opencontainers.image.vendor="Forum Virium Helsinki"
LABEL org.opencontainers.image.source="https://github.com/owner/repo"
org.opencontainers.image.description="Production API server"
org.opencontainers.image.licenses="MIT"
org.opencontainers.image.vendor="Forum Virium Helsinki"

Dynamic labels (via build args)

Dynamic labels (via build args)

ARG VERSION=dev ARG BUILD_DATE ARG VCS_REF
LABEL org.opencontainers.image.version="${VERSION}"
org.opencontainers.image.created="${BUILD_DATE}"
org.opencontainers.image.revision="${VCS_REF}"
undefined
ARG VERSION=dev ARG BUILD_DATE ARG VCS_REF
LABEL org.opencontainers.image.version="${VERSION}"
org.opencontainers.image.created="${BUILD_DATE}"
org.opencontainers.image.revision="${VCS_REF}"
undefined

Adding Labels at Build Time

构建时添加标签

bash
docker build \
  --label "org.opencontainers.image.source=https://github.com/owner/repo" \
  --label "org.opencontainers.image.description=My container image" \
  --label "org.opencontainers.image.licenses=MIT" \
  --build-arg VERSION=1.2.3 \
  --build-arg BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
  --build-arg VCS_REF=$(git rev-parse --short HEAD) \
  -t myapp:1.2.3 .
bash
docker build \
  --label "org.opencontainers.image.source=https://github.com/owner/repo" \
  --label "org.opencontainers.image.description=My container image" \
  --label "org.opencontainers.image.licenses=MIT" \
  --build-arg VERSION=1.2.3 \
  --build-arg BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \
  --build-arg VCS_REF=$(git rev-parse --short HEAD) \
  -t myapp:1.2.3 .

GitHub Actions with docker/metadata-action

GitHub Actions配合docker/metadata-action

The
docker/metadata-action
automatically generates OCI labels from repository metadata:
yaml
- id: meta
  uses: docker/metadata-action@v5
  with:
    images: ghcr.io/${{ github.repository }}
    labels: |
      org.opencontainers.image.title=My Application
      org.opencontainers.image.description=Production API server
      org.opencontainers.image.vendor=Forum Virium Helsinki

- uses: docker/build-push-action@v6
  with:
    labels: ${{ steps.meta.outputs.labels }}
Auto-generated labels by metadata-action:
  • org.opencontainers.image.source
    (from repository URL)
  • org.opencontainers.image.revision
    (from commit SHA)
  • org.opencontainers.image.created
    (build timestamp)
  • org.opencontainers.image.version
    (from tags/refs)
Skaffold Preference
  • Favor Skaffold over Docker Compose for local development
  • Continuous development loop with hot reload
  • Production-like local environment
docker/metadata-action
可自动从仓库元数据生成OCI标签:
yaml
- id: meta
  uses: docker/metadata-action@v5
  with:
    images: ghcr.io/${{ github.repository }}
    labels: |
      org.opencontainers.image.title=My Application
      org.opencontainers.image.description=Production API server
      org.opencontainers.image.vendor=Forum Virium Helsinki

- uses: docker/build-push-action@v6
  with:
    labels: ${{ steps.meta.outputs.labels }}
metadata-action自动生成的标签
  • org.opencontainers.image.source
    (来自仓库URL)
  • org.opencontainers.image.revision
    (来自提交SHA)
  • org.opencontainers.image.created
    (构建时间戳)
  • org.opencontainers.image.version
    (来自标签/引用)
Skaffold优先推荐
  • 本地开发优先使用Skaffold而非Docker Compose
  • 支持热重载的持续开发循环
  • 类生产环境的本地开发环境

Agentic Optimizations

智能优化技巧

When building and testing containers, use these optimizations for faster feedback:
ContextCommandPurpose
Quick build
DOCKER_BUILDKIT=1 docker build --progress=plain -t app .
BuildKit with plain output
Build with cache
docker build --cache-from app:latest -t app:new .
Reuse layers from previous builds
Security scan
docker scout cves app:latest | head -50
Quick vulnerability check
Size analysis
docker images app --format "{{.Size}}"
Check image size
Layer inspection
docker history app:latest --human --no-trunc
Analyze layer sizes
Build without cache
docker build --no-cache --progress=plain -t app .
Force clean build
Test container
docker run --rm -it app:latest /bin/sh
Interactive testing
Quick health check
docker run --rm app:latest timeout 5 /health
Verify startup
Build optimization flags:
  • --target=<stage>
    : Build specific stage only (faster iteration)
  • --build-arg BUILDKIT_INLINE_CACHE=1
    : Enable inline cache
  • --secret id=key,src=file
    : Mount secrets without including in image
For detailed Dockerfile optimization techniques, orchestration patterns, security hardening, and Skaffold configuration, see REFERENCE.md.
构建与测试容器时,使用以下命令提升反馈效率:
场景命令用途
快速构建
DOCKER_BUILDKIT=1 docker build --progress=plain -t app .
使用BuildKit并输出简洁日志
带缓存构建
docker build --cache-from app:latest -t app:new .
复用之前构建的镜像层
安全扫描
docker scout cves app:latest | head -50
快速检查漏洞
体积分析
docker images app --format "{{.Size}}"
查看镜像体积
镜像层分析
docker history app:latest --human --no-trunc
分析各镜像层体积
无缓存构建
docker build --no-cache --progress=plain -t app .
强制全量构建
容器测试
docker run --rm -it app:latest /bin/sh
交互式测试
快速健康检查
docker run --rm app:latest timeout 5 /health
验证启动状态
构建优化参数
  • --target=<stage>
    :仅构建指定阶段(加速迭代)
  • --build-arg BUILDKIT_INLINE_CACHE=1
    :启用内联缓存
  • --secret id=key,src=file
    :挂载密钥但不加入镜像
关于Dockerfile优化技巧、编排模式、安全加固与Skaffold配置的详细内容,请参考REFERENCE.md。

Related Skills

相关技能

Language-Specific Container Optimization:
  • go-containers
    - Go static binaries, scratch/distroless (846MB → 2.5MB)
  • nodejs-containers
    - Node.js Alpine patterns, npm/yarn/pnpm (900MB → 100MB)
  • python-containers
    - Python slim (NOT Alpine), uv/poetry (1GB → 100MB)
语言专属容器优化
  • go-containers
    - Go静态二进制文件、scratch/distroless镜像(846MB → 2.5MB)
  • nodejs-containers
    - Node.js Alpine镜像实践、npm/yarn/pnpm(900MB → 100MB)
  • python-containers
    - Python slim镜像(禁止用Alpine)、uv/poetry(1GB → 100MB)

Related Commands

相关命令

  • /configure:container
    - Comprehensive container infrastructure validation
  • /configure:dockerfile
    - Dockerfile-specific configuration
  • /configure:workflows
    - GitHub Actions including container builds
  • /configure:skaffold
    - Kubernetes development configuration
  • /configure:container
    - 全面的容器基础设施验证
  • /configure:dockerfile
    - Dockerfile专属配置
  • /configure:workflows
    - 包含容器构建的GitHub Actions配置
  • /configure:skaffold
    - Kubernetes开发环境配置