Docker Patterns 标志

Docker Patterns

组织
cosmicstack-labs
docker-patterns

Master Dockerfile optimization, multi-stage builds, docker-compose patterns, security hardening, and image size reduction techniques for production-grade containerization.

概览

发布者cosmicstack-labs
代码仓库mercury-agent-skills
技能名称docker-patterns
星标数
485
复刻数
63
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 cosmicstack-labs 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Docker Patterns AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/devops/docker-patterns
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/cosmicstack-labs/mercury-agent-skills.git /tmp/mercury-agent-skills
mkdir -p .claude/skills
cp -r /tmp/mercury-agent-skills/categories/devops/docker-patterns .claude/skills/docker-patterns
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Docker Patterns,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Docker Patterns。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Docker Patterns 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

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):

dockerfile
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:

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:

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:

dockerfile
# 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:

dockerfile
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
dockerfile
# 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:
    dockerfile
    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:

dockerfile
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:

yaml
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:

yaml
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:

yaml
services:
  app:
    depends_on:
      db:
        condition: service_healthy

4. Security Best Practices

Never Run as Root:

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

Read-Only Root Filesystem:

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

Drop Capabilities:

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

Security Scanning with Trivy:

bash
# 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:

bash
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:

dockerfile
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 context — COPY . /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.

常见问题

Docker Patterns AI 技能有什么作用?

Master Dockerfile optimization, multi-stage builds, docker-compose patterns, security hardening, and image size reduction techniques for production-grade containerization.

为什么在 TypingMind 中使用 Docker Patterns?

因为您只需安装一次,就能搭配任何模型使用。Docker Patterns 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Docker Patterns?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/devops/docker-patterns。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Docker Patterns?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Docker Patterns 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Docker Patterns 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Docker Patterns AI 技能免费吗?

是的。cosmicstack-labs 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇