---
name: "docker-multistage-build-opt"
description: "Construct minimal, high-speed production Docker images using multi-stage builds and cache mounts."
metadata:
  author: "Docker"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "write multistage dockerfile"
  - "optimize docker layer cache"
  - "shrink docker image size"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# Docker Multi-Stage Build & Layer Cache Optimization

Applies multi-stage Dockerfile patterns: separating builder from runtime stages, leveraging BuildKit cache mounts (--mount=type=cache), ordering layers by change frequency, and stripping unnecessary compilers to shrink images by 80%.

## When to Invoke
Invoke this skill whenever you need to:
- write multistage dockerfile
- optimize docker layer cache
- shrink docker image size

## Execution SOP & Rules
1. Define separate AS builder and final runner stages in Dockerfile.
2. Mount package manager caches: RUN --mount=type=cache,target=/root/.npm npm ci.
3. Copy only compiled production artifacts from builder stage into minimal base image (alpine / distroless).
4. Enforce non-root USER directive and verify final image size using docker images.

## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.
