docker-patternslisted
Install: claude install-skill sardonyx0827/dotfiles
# Docker Patterns
Container best practices for fast builds, small images, and secure runtimes.
## 1. Multi-Stage Builds
Use separate build and runtime stages. The runtime stage should contain only the compiled
artifact — never the toolchain, source code, or build-time dependencies. This is the
single biggest lever for reducing final image size.
```dockerfile
# ❌ WRONG: single stage ships the full Node.js toolchain and source
FROM node:20
WORKDIR /app
COPY . .
RUN npm ci && npm run build
CMD ["node", "dist/server.js"]
# ✅ CORRECT: build stage compiles; runtime stage ships only the artifact
FROM node:20-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-slim AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]
```
Go example — the runtime image can be distroless or scratch because Go produces a
statically-linked binary:
```dockerfile
FROM golang:1.22 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server ./cmd/server
FROM gcr.io/distroless/static-debian12 AS runtime
COPY --from=builder /app/server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]
```
## 2. Layer Caching
Order instructions from least-volatile to most-volatile. Docker invalidates every layer
below the first changed layer; a misplaced `COPY . .` before `npm ci` means dependencies
are re-downloaded on