container-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseContainer 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
镜像制作流程
- Analyze: Understand application dependencies and build process
- Structure: Design multi-stage Dockerfile, separating build-time from runtime needs
- Ignore: Create comprehensive file
.dockerignore - Build & Scan: Build image and scan for vulnerabilities
- Refine: Iterate to optimize layer caching, reduce size, address security
- Validate: Ensure image runs correctly and adheres to 12-factor principles
- 分析:梳理应用依赖与构建流程
- 架构设计:设计多阶段Dockerfile,分离构建时与运行时需求
- 忽略配置:创建全面的文件
.dockerignore - 构建与扫描:构建镜像并进行漏洞扫描
- 优化迭代:迭代优化镜像缓存、减小体积、修复安全问题
- 验证:确保镜像正常运行且符合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:
- Node.js Alpine: Check Docker Hub node for latest LTS
- Python slim: Check Docker Hub python for latest
- Go Alpine: Check Docker Hub golang for latest
- nginx Alpine: Check Docker Hub nginx
- Distroless: Check Google distroless for latest
Use WebSearch or WebFetch to verify current versions.
关键:使用基础镜像前,务必验证最新版本:
- Node.js Alpine:查看Docker Hub node获取最新LTS版本
- Python slim:查看Docker Hub python获取最新版本
- Go Alpine:查看Docker Hub golang获取最新版本
- nginx Alpine:查看Docker Hub nginx
- Distroless:查看Google distroless获取最新版本
使用WebSearch或WebFetch验证当前版本。
Language-Specific Optimization
语言专属优化
For detailed language-specific optimization patterns, see the dedicated skills:
| Language | Skill | Key Optimization | Typical Reduction |
|---|---|---|---|
| Go | | Static binaries, scratch/distroless | 846MB → 2.5MB (99.7%) |
| Node.js | | Alpine, multi-stage, npm/yarn/pnpm | 900MB → 100MB (89%) |
| Python | | Slim (NOT Alpine), uv, venv | 1GB → 100MB (90%) |
关于各语言的详细优化模式,请参考专属技能:
| 语言 | Skill | 核心优化点 | 典型压缩比例 |
|---|---|---|---|
| Go | | Static binaries, scratch/distroless | 846MB → 2.5MB (99.7%) |
| Node.js | | Alpine, multi-stage, npm/yarn/pnpm | 900MB → 100MB (89%) |
| Python | | Slim (NOT Alpine), uv, venv | 1GB → 100MB (90%) |
Quick Base Image Guide
快速基础镜像指南
Choose the right base image:
- Go: or
scratch(2-5MB)distroless/static - Node.js: (50-150MB)
node:XX-alpine - Python: (80-120MB) - Never use Alpine for Python!
python:XX-slim - Nginx: (20-40MB)
nginx:XX-alpine - Static files: or
scratch(minimal)nginx:alpine
选择合适的基础镜像:
- Go:或
scratch(2-5MB)distroless/static - Node.js:(50-150MB)
node:XX-alpine - Python:(80-120MB)- Python绝对不要用Alpine!
python:XX-slim - Nginx:(20-40MB)
nginx:XX-alpine - 静态文件:或
scratch(极致轻量)nginx:alpine
Multi-Stage Build Template
多阶段构建模板
dockerfile
undefineddockerfile
undefinedBuild 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
adduser --uid 1001 --gid 1001 --disabled-password appuser
RUN addgroup --gid 1001 appgroup &&
adduser --uid 1001 --gid 1001 --disabled-password appuser
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 handlingCOPY --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必填标签
| Label | Purpose | Example |
|---|---|---|
| Links image to repository (enables GHCR features) | |
| Package description (max 512 chars) | |
| SPDX license identifier (max 256 chars) | |
| 标签 | 用途 | 示例 |
|---|---|---|
| 关联镜像到代码仓库(启用GHCR专属功能) | |
| 包描述(最多512字符) | |
| SPDX许可证标识(最多256字符) | |
Recommended Labels
推荐标签
| Label | Purpose | Example |
|---|---|---|
| Semantic version | |
| Git commit SHA | |
| Build timestamp (RFC 3339) | |
| Human-readable name | |
| Organization name | |
| Project homepage | |
| Documentation URL | |
| 标签 | 用途 | 示例 |
|---|---|---|
| 语义化版本 | |
| Git提交SHA | |
| 构建时间戳(RFC 3339格式) | |
| 人类可读名称 | |
| 组织名称 | |
| 项目主页 | |
| 文档地址 | |
Adding Labels in Dockerfile
在Dockerfile中添加标签
dockerfile
undefineddockerfile
undefinedStatic 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"
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"
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}"
org.opencontainers.image.created="${BUILD_DATE}"
org.opencontainers.image.revision="${VCS_REF}"
undefinedARG 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}"
org.opencontainers.image.created="${BUILD_DATE}"
org.opencontainers.image.revision="${VCS_REF}"
undefinedAdding 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 automatically generates OCI labels from repository metadata:
docker/metadata-actionyaml
- 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:
- (from repository URL)
org.opencontainers.image.source - (from commit SHA)
org.opencontainers.image.revision - (build timestamp)
org.opencontainers.image.created - (from tags/refs)
org.opencontainers.image.version
Skaffold Preference
- Favor Skaffold over Docker Compose for local development
- Continuous development loop with hot reload
- Production-like local environment
docker/metadata-actionyaml
- 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自动生成的标签:
- (来自仓库URL)
org.opencontainers.image.source - (来自提交SHA)
org.opencontainers.image.revision - (构建时间戳)
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:
| Context | Command | Purpose |
|---|---|---|
| Quick build | | BuildKit with plain output |
| Build with cache | | Reuse layers from previous builds |
| Security scan | | Quick vulnerability check |
| Size analysis | | Check image size |
| Layer inspection | | Analyze layer sizes |
| Build without cache | | Force clean build |
| Test container | | Interactive testing |
| Quick health check | | Verify startup |
Build optimization flags:
- : Build specific stage only (faster iteration)
--target=<stage> - : Enable inline cache
--build-arg BUILDKIT_INLINE_CACHE=1 - : Mount secrets without including in image
--secret id=key,src=file
For detailed Dockerfile optimization techniques, orchestration patterns, security hardening, and Skaffold configuration, see REFERENCE.md.
构建与测试容器时,使用以下命令提升反馈效率:
| 场景 | 命令 | 用途 |
|---|---|---|
| 快速构建 | | 使用BuildKit并输出简洁日志 |
| 带缓存构建 | | 复用之前构建的镜像层 |
| 安全扫描 | | 快速检查漏洞 |
| 体积分析 | | 查看镜像体积 |
| 镜像层分析 | | 分析各镜像层体积 |
| 无缓存构建 | | 强制全量构建 |
| 容器测试 | | 交互式测试 |
| 快速健康检查 | | 验证启动状态 |
构建优化参数:
- :仅构建指定阶段(加速迭代)
--target=<stage> - :启用内联缓存
--build-arg BUILDKIT_INLINE_CACHE=1 - :挂载密钥但不加入镜像
--secret id=key,src=file
关于Dockerfile优化技巧、编排模式、安全加固与Skaffold配置的详细内容,请参考REFERENCE.md。
Related Skills
相关技能
Language-Specific Container Optimization:
- - Go static binaries, scratch/distroless (846MB → 2.5MB)
go-containers - - Node.js Alpine patterns, npm/yarn/pnpm (900MB → 100MB)
nodejs-containers - - Python slim (NOT Alpine), uv/poetry (1GB → 100MB)
python-containers
语言专属容器优化:
- - Go静态二进制文件、scratch/distroless镜像(846MB → 2.5MB)
go-containers - - Node.js Alpine镜像实践、npm/yarn/pnpm(900MB → 100MB)
nodejs-containers - - Python slim镜像(禁止用Alpine)、uv/poetry(1GB → 100MB)
python-containers
Related Commands
相关命令
- - Comprehensive container infrastructure validation
/configure:container - - Dockerfile-specific configuration
/configure:dockerfile - - GitHub Actions including container builds
/configure:workflows - - Kubernetes development configuration
/configure:skaffold
- - 全面的容器基础设施验证
/configure:container - - Dockerfile专属配置
/configure:dockerfile - - 包含容器构建的GitHub Actions配置
/configure:workflows - - Kubernetes开发环境配置
/configure:skaffold