docker-patterns

GitHub

掌握生产级Docker化最佳实践,涵盖Dockerfile优化、多阶段构建、Compose编排、安全加固及镜像精简。指导用户从基础到熟练,遵循极简、可复现、缓存高效等核心原则,构建高效安全的容器环境。

categories/devops/docker-patterns/SKILL.md cosmicstack-labs/mercury-agent-skills

Trigger Scenarios

优化Dockerfile性能 配置多阶段构建 减少Docker镜像体积 加固容器安全性 使用docker-compose编排服务

Install

npx skills add cosmicstack-labs/mercury-agent-skills --skill docker-patterns -g -y
More Options

Non-standard path

npx skills add https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/devops/docker-patterns -g -y

Use without installing

npx skills use cosmicstack-labs/mercury-agent-skills@docker-patterns

指定 Agent (Claude Code)

npx skills add cosmicstack-labs/mercury-agent-skills --skill docker-patterns -a claude-code -g -y

安装 repo 全部 skill

npx skills add cosmicstack-labs/mercury-agent-skills --all -g -y

预览 repo 内 skill

npx skills add cosmicstack-labs/mercury-agent-skills --list

SKILL.md

Frontmatter
{
    "name": "docker-patterns",
    "metadata": {
        "tags": [
            "docker",
            "containerization",
            "devops",
            "security",
            "build-optimization",
            "dockerfile",
            "docker-compose",
            "multi-stage-builds"
        ],
        "author": "cosmicstack-labs",
        "version": "1.0.0",
        "category": "devops"
    },
    "description": "Master Dockerfile optimization, multi-stage builds, docker-compose patterns, security hardening, and image size reduction techniques for production-grade containerization."
}

Docker Patterns: Production-Grade Containerization

Overview

Docker patterns encompass the art and science of building efficient, secure, and maintainable container images. This skill covers the entire lifecycle — from writing optimized Dockerfiles and orchestrating multi-service environments with docker-compose to hardening images against vulnerabilities and minimizing attack surface. Mastery of these patterns is essential for any DevOps practitioner aiming to ship reliable, fast, and secure software.


Core Principles

  1. Minimalism — Every layer, every package, every instruction adds weight and risk. Include only what the runtime needs, nothing more.
  2. Reproducibility — Builds must produce identical images given the same source. Pin base image tags, lock dependency versions, and avoid network-dependent build steps.
  3. Cache Efficiency — Order Dockerfile instructions from least to most frequently changing to maximize layer cache reuse. This transforms build times from minutes to seconds.
  4. Defense in Depth — Never run containers as root. Use read-only root filesystems. Drop all unnecessary Linux capabilities. Scan images before deployment.
  5. Single Responsibility — Each container should run exactly one process. Use docker-compose to compose multiple containers rather than cramming processes into one image.
  6. Immutable Infrastructure — Never modify a running container. Build a new image, test it, and replace the old one. This eliminates configuration drift.

Docker Maturity Model

🟢 Beginner

  • Uses a single FROM statement in Dockerfiles
  • Runs containers as root by default
  • Installs build tools and runtime dependencies in the same layer
  • No .dockerignore file
  • Pulls :latest base image tags
  • Uses docker commit for ad-hoc image creation
  • Builds take 5–15 minutes with no layer caching strategy
  • Image sizes range from 500 MB to 2+ GB

Typical Beginner Dockerfile (anti-pattern):

FROM node:latest
RUN apt-get update && apt-get install -y build-essential
COPY . /app
WORKDIR /app
RUN npm install
RUN npm run build
CMD ["npm", "start"]

🟡 Proficient

  • Uses multi-stage builds to separate build and runtime environments
  • Leverages official slim or alpine base images (e.g., node:20-slim)
  • Creates and uses .dockerignore files
  • Pins specific base image digests (node:20-slim@sha256:...)
  • Orders Dockerfile layers for optimal caching (dependencies before source)
  • Runs containers with a non-root user
  • Uses docker scan or trivy for vulnerability scanning
  • Image sizes: 100–300 MB
  • Build times: 1–3 minutes

Proficient Dockerfile:

# Stage 1: Build
FROM node:20-slim AS builder
WORKDIR /build
COPY package.json package-lock.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build

# Stage 2: Runtime
FROM node:20-slim AS runtime
RUN groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
COPY --from=builder /build/dist ./dist
COPY --from=builder /build/node_modules ./node_modules
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s \
  CMD node healthcheck.js
CMD ["node", "dist/server.js"]

🔴 Expert

  • Distroless or scratch-based runtime images for minimal attack surface
  • BuildKit cache mounts and --mount=type=cache for zero-copy dependency installs
  • Custom base images with pre-hardened OS configurations
  • SBOM (Software Bill of Materials) generation with docker sbom or syft
  • Signed images with Docker Content Trust (DCT) or cosign
  • Runtime security profiles: seccomp, AppArmor, and SELinux policies
  • Dockerfile linting with hadolint integrated into CI
  • Image size: 10–50 MB for compiled languages, 80–150 MB for interpreted
  • Build times: 15–45 seconds
  • Automatic base image vulnerability patching with Dependabot/Renovate

Expert Dockerfile:

# syntax=docker/dockerfile:1.7
# Stage 1: Build with cache mounts
FROM golang:1.22-alpine AS builder
RUN apk add --no-cache ca-certificates
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app .

# Stage 2: Distroless runtime
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /app /app
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/app"]

Actionable Guidance

1. Multi-Stage Builds

Multi-stage builds use multiple FROM statements in a single Dockerfile. Each stage can use a different base image. Only the final stage is saved in the image — intermediate stages are discarded.

Why they matter:

  • Build tools (compilers, dev dependencies) are isolated in build stages
  • Runtime images contain only binaries and essentials
  • Dramatically reduces image size and attack surface

Pattern — Build and Copy Artifacts:

# Build stage
FROM python:3.12-slim AS builder
COPY requirements.txt .
RUN pip install --user -r requirements.txt

# Runtime stage
FROM python:3.12-slim
COPY --from=builder /root/.local /root/.local
COPY app/ ./app
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app/main.py"]

Pattern — Conditional Stages with Build Args:

ARG BUILD_ENV=production

FROM node:20-alpine AS base
WORKDIR /app
COPY package*.json ./

FROM base AS development
RUN npm install --include=dev
COPY . .

FROM base AS production
RUN npm ci --only=production
COPY . .
RUN npm run build

FROM ${BUILD_ENV}
CMD ["node", "dist/server.js"]

2. Dockerfile Best Practices

Layer Caching Strategy:

  • Copy package.json / requirements.txt before source code — dependency install layers only invalidate when dependencies change
  • Combine RUN apt-get update with apt-get install in the same layer to avoid stale cache issues
  • Use --no-cache or --no-install-recommends flags to reduce size
# GOOD: Dependencies before source
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# BAD: Source before dependencies — invalidates cache on every code change
COPY . .
RUN pip install -r requirements.txt

.dockerignore File: Always create a .dockerignore to exclude files from the build context:

node_modules
.git
.env
*.md
coverage
.gitignore
Dockerfile
.dockerignore
dist
.cache
npm-debug.log

Image Size Optimization:

  • Prefer -slim variants over full images
  • Use -alpine for even smaller sizes when compatibility allows
  • Clean up package manager caches in the same RUN layer:
    RUN apt-get update && \
        apt-get install -y --no-install-recommends curl && \
        apt-get clean && \
        rm -rf /var/lib/apt/lists/*
    
  • Remove temporary files within the same RUN instruction

Health Checks:

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8080/health || exit 1

3. Docker Compose Patterns

Service Composition:

version: "3.9"
services:
  api:
    build:
      context: .
      target: production
      cache_from:
        - myapp/api:latest
    ports:
      - "8080:8080"
    environment:
      - DB_HOST=db
      - REDIS_HOST=redis
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
    volumes:
      - type: volume
        source: app_data
        target: /app/data

  db:
    image: postgres:16-alpine
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_DB: myapp
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U myapp"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data
    command: redis-server --appendonly yes

volumes:
  pgdata:
  redis_data:
  app_data:

secrets:
  db_password:
    file: ./secrets/db_password.txt

Development vs Production Profiles:

services:
  app:
    build: .
    profiles: ["dev", "prod"]

  mailhog:
    image: mailhog/mailhog
    profiles: ["dev"]
    ports: ["8025:8025"]

  prometheus:
    image: prom/prometheus
    profiles: ["prod"]

Start dev: docker compose --profile dev up

Docker Compose Health Check Wait Pattern:

services:
  app:
    depends_on:
      db:
        condition: service_healthy

4. Security Best Practices

Never Run as Root:

RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

Read-Only Root Filesystem:

services:
  app:
    read_only: true
    tmpfs:
      - /tmp

Drop Capabilities:

services:
  app:
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE

Security Scanning with Trivy:

# Scan image
trivy image --severity HIGH,CRITICAL myapp:latest

# Scan Dockerfile for misconfigurations
trivy config --severity HIGH,CRITICAL Dockerfile

# CI integration
trivy image --exit-code 1 --severity CRITICAL myapp:latest

Docker Bench Security:

docker run --privileged --pid=host \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v /etc:/etc:ro \
  docker/docker-bench-security

Use Specific Image Digests:

FROM node:20-slim@sha256:abc123def456...

Common Mistakes

  1. Using :latest — Unpinned tags cause unpredictable builds. Always pin to a specific version or digest.

  2. Copying entire contextCOPY . /app sends the entire directory including node_modules, .git, and secrets. Use .dockerignore and specific COPY paths.

  3. Installing unnecessary packages — Every package is a potential vulnerability. Use --no-install-recommends and prefer distroless images.

  4. Multiple services in one container — Containers should run one process. Use docker-compose for multi-service architectures.

  5. Storing secrets in images — Secrets in Dockerfile layers persist even if the layer is removed. Use Docker secrets, BuildKit secrets, or external secret stores.

  6. Ignoring layer ordering — Putting code before dependencies destroys cache efficiency. Always structure Dockerfiles for optimal layer caching.

  7. Skipping health checks — Without health checks, orchestration platforms can't determine actual container readiness.

  8. Running as root — Root in a container is root on the host if the container escapes. Always use a non-root user.

  9. No vulnerability scanning — Images accumulate CVEs over time. Scan in CI and set thresholds to fail builds on critical/high vulnerabilities.

  10. Overly permissive compose volumes.:/app bind mounts expose the host filesystem. Use named volumes or specific host paths instead.

Version History

  • 38e2523 Current 2026-07-05 19:39

Same Skill Collection

categories/ai-ml/agent-audit-logging/SKILL.md
categories/ai-ml/agent-handoff-protocols/SKILL.md
categories/ai-ml/agent-health-monitoring/SKILL.md
categories/ai-ml/agent-task-delegation/SKILL.md
categories/ai-ml/ai-agent-design/SKILL.md
categories/ai-ml/error-recovery-retry/SKILL.md
categories/ai-ml/memory-management/SKILL.md
categories/ai-ml/prompt-engineering/SKILL.md
categories/ai-ml/prompt-version-management/SKILL.md
categories/ai-ml/token-budget-tracking/SKILL.md
categories/automation/daily-briefing/SKILL.md
categories/automation/screenshot/SKILL.md
categories/automation/shell-scripting/SKILL.md
categories/automation/twitter-account-manager/SKILL.md
categories/automation/workflow-automation/SKILL.md
categories/automation/x-twitter-automation/SKILL.md
categories/backend/api-design/SKILL.md
categories/backend/authentication-authorization/SKILL.md
categories/backend/caching-strategies/SKILL.md
categories/backend/database-design/SKILL.md
categories/backend/message-queues/SKILL.md
categories/backend/microservices/SKILL.md
categories/backend/nodejs-patterns/SKILL.md
categories/backend/python-patterns/SKILL.md
categories/backend/serverless-patterns/SKILL.md
categories/business/event-staffing-compliance/SKILL.md
categories/business/event-staffing-ordering/SKILL.md
categories/business/negotiation/SKILL.md
categories/business/startup-strategy/SKILL.md
categories/career/career-planning/SKILL.md
categories/career/interview-prep/SKILL.md
categories/career/linkedin-optimization/SKILL.md
categories/career/resume-writing/SKILL.md
categories/career/salary-negotiation/SKILL.md
categories/creative-personal-development/content-repurposer/SKILL.md
categories/creative-personal-development/daily-standup-journal/SKILL.md
categories/creative-personal-development/decision-matrix/SKILL.md
categories/creative-personal-development/idea-validator/SKILL.md
categories/creative-personal-development/meeting-note-summarizer/SKILL.md
categories/creative-personal-development/personal-branding-statement/SKILL.md
categories/creative-personal-development/storytelling-advisor/SKILL.md
categories/creative-personal-development/time-blocking-scheduler/SKILL.md
categories/data/data-pipeline/SKILL.md
categories/design/accessibility/SKILL.md
categories/design/ui-design-system/SKILL.md
categories/development/api-documentation/SKILL.md
categories/development/architecture-decision-records/SKILL.md
categories/development/clean-code/SKILL.md
categories/development/code-review/SKILL.md
categories/development/debugging-mastery/SKILL.md
categories/development/dependency-management/SKILL.md
categories/development/documentation-generation/SKILL.md
categories/development/git-workflow/SKILL.md
categories/development/hyperframes-cli/SKILL.md
categories/development/hyperframes-media/SKILL.md
categories/development/knowledge-base/SKILL.md
categories/development/markdown-mastery/SKILL.md
categories/development/refactoring-patterns/SKILL.md
categories/development/technical-writing/SKILL.md
categories/development/testing-strategies/SKILL.md
categories/devops/ci-cd-pipeline/SKILL.md
categories/devops/cloud-architecture/SKILL.md
categories/devops/kubernetes-patterns/SKILL.md
categories/devops/monitoring-observability/SKILL.md
categories/devops/sre-practices/SKILL.md
categories/devops/terraform-iac/SKILL.md
categories/education-learning/assessment-design/SKILL.md
categories/education-learning/learning-science/SKILL.md
categories/education-learning/micro-learning/SKILL.md
categories/education-learning/teaching-methods/SKILL.md
categories/finance-legal/budgeting-forecasting/SKILL.md
categories/finance-legal/contract-review/SKILL.md
categories/finance-legal/financial-analysis/SKILL.md
categories/finance-legal/privacy-compliance/SKILL.md
categories/finance-legal/risk-management/SKILL.md
categories/frontend/component-design-systems/SKILL.md
categories/frontend/frontend-testing/SKILL.md
categories/frontend/nextjs-patterns/SKILL.md
categories/frontend/react-patterns/SKILL.md
categories/frontend/responsive-design/SKILL.md
categories/frontend/state-management/SKILL.md
categories/frontend/tailwind-css/SKILL.md
categories/frontend/web-performance/SKILL.md
categories/health-wellness/fitness-planning/SKILL.md
categories/health-wellness/habit-formation/SKILL.md
categories/health-wellness/mental-health/SKILL.md
categories/health-wellness/nutrition-planning/SKILL.md
categories/health-wellness/sleep-optimization/SKILL.md
categories/marketing/content-creation/SKILL.md
categories/marketing/local-business-growth/SKILL.md
categories/marketing/seo-strategy/SKILL.md
categories/media-download/audio-extraction/SKILL.md
categories/media-download/github-repo-promo/SKILL.md
categories/media-download/github-repo-tour/SKILL.md
categories/media-download/legal-downloading/SKILL.md
categories/media-download/playlist-archiver/SKILL.md
categories/media-download/video-downloader/SKILL.md
categories/mobile/android-kotlin-patterns/SKILL.md
categories/mobile/app-store-optimization/SKILL.md
categories/mobile/ios-swift-patterns/SKILL.md
categories/mobile/mobile-performance/SKILL.md
categories/mobile/react-native-patterns/SKILL.md
categories/pdf-generation/invoice-document-pdf/SKILL.md
categories/pdf-generation/markdown-to-pdf/SKILL.md
categories/pdf-generation/report-generation/SKILL.md
categories/pdf-generation/typesetting-latex/SKILL.md
categories/presentation/data-storytelling/SKILL.md
categories/presentation/pitch-deck-creation/SKILL.md
categories/presentation/presentation-automation/SKILL.md
categories/presentation/presentation-design/SKILL.md
categories/product/product-strategy/SKILL.md
categories/product/user-research/SKILL.md
categories/security/security-audit/SKILL.md
categories/shop-restaurant/amazon-assistant/SKILL.md
categories/shop-restaurant/daily-pulse/SKILL.md
categories/shop-restaurant/inventory-optimizer/SKILL.md
categories/shop-restaurant/menu-engineer/SKILL.md
categories/shop-restaurant/price-scout/SKILL.md
categories/shop-restaurant/review-responder/SKILL.md
categories/shop-restaurant/social-post/SKILL.md
categories/shop-restaurant/staff-scheduler/SKILL.md
categories/shop-restaurant/table-manager/SKILL.md
categories/shop-restaurant/zomato-order/SKILL.md
categories/testing-qa/accessibility-testing/SKILL.md
categories/testing-qa/api-testing/SKILL.md
categories/testing-qa/e2e-testing/SKILL.md
categories/testing-qa/performance-testing/SKILL.md
categories/testing-qa/test-strategy/SKILL.md
categories/ai-ml/gbrain-lite/SKILL.md
categories/development/hyperframes/SKILL.md
categories/pdf-generation/any2pdf/SKILL.md

Metadata

Files
0
Version
38e2523
Hash
b7a2c3c2
Indexed
2026-07-05 19:39

Главная - Вики-сайт
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-08 23:24
浙ICP备14020137号-1 $Гость$