NovFora Dev

[Question] How to reduce Docker build times using multi-stage builds and cache mounts?

Taylor Davis

Taylor Davis

4 months ago

Multi-stage builds let you separate build-time dependencies from your final production image, keeping it small and secure. For even faster builds, use --mount=type=cache for package managers like pip or npm — this caches downloaded packages between runs rather than re-downloading everything on every rebuild. Order your Dockerfile commands carefully: copy only what's necessary before running heavy operations to maximize layer caching.

Taylor Davis

Taylor Davis

4 months ago

Two techniques that compound:

Multi-stage builds. Build your app in a heavy image (Go, Node with devDependencies) and copy the binary/build artifacts to a tiny production image (scratch, alpine). This keeps final images small AND gives you two cache layers — one for build dependencies, one for runtime.

# Stage 1: build
FROM golang:1.23-bookworm AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download  <-- this layer is cached as long as go.mod doesn't change
COPY . .
RUN go build -o myapp main.go

# Stage 2: production
FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/myapp .
CMD ["./myapp"]

BuildKit cache mounts (--mount=type=cache). This is the real speed hack for

Join the conversation to leave a reply.

Sign in to reply

Related topics