AgentSkillsCN

Docker Patterns

Docker 模式

SKILL.md

Docker Patterns Skill

Purpose

Best practices for containerization with Docker and orchestration.

Auto-Invoke Triggers

  • Creating Dockerfiles
  • Setting up docker-compose
  • Optimizing container images
  • Configuring container security

Dockerfile Best Practices

Image Selection

LanguageRecommended Base
Pythonpython:3.12-slim
Node.jsnode:20-alpine
Gogolang:1.21-alpine (build), scratch (runtime)

Layer Optimization

  • Order commands from least to most frequently changing
  • Combine RUN commands to reduce layers
  • Copy dependency files before source code
  • Use .dockerignore to exclude unnecessary files

Multi-Stage Build Pattern

code
Stage 1: Build (full SDK, compile code)
    ↓
Stage 2: Runtime (slim image, only artifacts)

Benefits:

  • Smaller final image
  • No build tools in production
  • Faster deployment
  • Reduced attack surface

Image Size Optimization

Strategies

StrategyImpact
Use slim/alpine base50-80% reduction
Multi-stage builds50-90% reduction
Remove cache after install10-30% reduction
Use .dockerignoreVariable

Target Sizes

App TypeTarget Size
Python API< 200MB
Node.js API< 150MB
Go binary< 50MB

.dockerignore Essentials

code
.git
.gitignore
node_modules
__pycache__
*.pyc
.env*
.vscode
.idea
tests
docs
*.md

Security Best Practices

Rules

  • Don't run as root (use non-root user)
  • Don't store secrets in images
  • Use specific image tags (not latest)
  • Scan images for vulnerabilities
  • Minimize installed packages
  • Use read-only filesystem where possible

User Configuration

  • Create non-root user
  • Set USER directive before CMD
  • Use numeric UID for Kubernetes compatibility

Secret Handling

  • Use environment variables at runtime
  • Use Docker secrets for Swarm
  • Use volume mounts for sensitive files
  • Never COPY secrets into image

Health Checks

Configuration

SettingRecommended
Interval30s
Timeout10s
Retries3
Start period30s

Health Check Types

TypeEndpointUse Case
HTTP/healthWeb APIs
TCPPort checkDatabases
CommandCustom scriptComplex checks

Health Response

  • Return 200 for healthy
  • Return 503 for unhealthy
  • Include dependency status
  • Keep checks lightweight

Docker Compose

Service Organization

Service TypePort Pattern
Frontend3000:80
Backend API8000:8000
Database5432:5432
Cache6379:6379

Network Strategy

  • Use custom bridge network
  • Don't expose ports unless necessary
  • Use service names for internal communication
  • Isolate databases on separate network

Volume Types

TypeUse Case
Named volumeDatabase data
Bind mountDevelopment code
tmpfsTemporary/sensitive data

Environment Configuration

Variable Hierarchy

  1. Environment variables (highest priority)
  2. .env file
  3. docker-compose.yml defaults
  4. Dockerfile defaults (lowest)

Environment Files

FilePurpose
.envLocal defaults
.env.exampleTemplate (committed)
.env.localLocal overrides
.env.productionProduction values

Configuration Rules

  • Don't commit .env files with secrets
  • Provide .env.example with placeholders
  • Validate required variables at startup
  • Use different values per environment

Development vs Production

Development

  • Mount source code as volume
  • Enable hot reload
  • Expose debug ports
  • Use development dependencies
  • Verbose logging

Production

  • Copy only built artifacts
  • No source code in image
  • Minimal base image
  • No development dependencies
  • Structured logging

Logging

Rules

  • Log to stdout/stderr
  • Use JSON format for production
  • Don't log to files inside container
  • Use logging drivers for aggregation

Log Drivers

DriverUse Case
json-fileDevelopment
fluentdProduction (ELK)
awslogsAWS CloudWatch
gcplogsGoogle Cloud

Resource Limits

Recommended Limits

ResourceDevelopmentProduction
Memory512MBBased on app
CPU0.5Based on app
PIDs100100

Setting Rules

  • Always set memory limits
  • Set CPU limits for shared hosts
  • Monitor actual usage before setting
  • Leave headroom for spikes

Best Practices

DO

  • Use multi-stage builds
  • Pin image versions
  • Use non-root user
  • Add health checks
  • Use .dockerignore
  • Scan for vulnerabilities

DON'T

  • Use latest tag
  • Run as root
  • Store secrets in images
  • Install unnecessary packages
  • Ignore layer caching
  • Skip health checks

Docker Checklist

Dockerfile

  • Uses slim/alpine base
  • Multi-stage build
  • Non-root user
  • Specific image tag
  • Health check defined
  • .dockerignore exists

Security

  • No secrets in image
  • Image scanned
  • Minimal packages
  • User not root

Configuration

  • Environment variables used
  • Resource limits set
  • Logging to stdout
  • Graceful shutdown handled