- Published on
Smaller and Faster Docker Images: The Complete Node.js and Go Guide
Contents
- Introduction
- The Modern BuildKit Pipeline
- Part 1: Ways to Make Docker Images Smaller
- 1. Multi-Stage Builds (Always Strip the Builder)
- 2. Pick the Smallest Safe Runtime Base Image
- 3. Go-Specific Binary Shrinking
- 4. Node.js-Specific Size Reductions
- 5. Write a Strict .dockerignore
- 6. Clean Package Caches in the Same Layer (or Never Write Them)
- 7. Switch OCI Compression from gzip to zstd (and Keep Layer Digests Stable)
- 8. Audit Layer Bloat With dive and buildx
- Part 2: Every Way to Make Docker Builds Faster
- 1. Order Instructions From Least-Changed to Most-Changed
- 2. Use BuildKit Cache Mounts (RUN --mount=type=cache)
- 3. Decouple Layers With COPY --link
- 4. Use COPY --exclude, Bind Mounts, and tmpfs
- 5. Eliminate QEMU Emulation With $BUILDPLATFORM
- 6. Structure Stages for Parallel Execution
- 7. Persist Cache in CI/CD With docker-container + mode=max
- 8. Catch Mistakes in Under a Second With docker build --check
- Complete Production Examples
- Summary: The 80/20 Checklist
Introduction
Slow Docker builds burn CI minutes on every pull request, and bloated container images waste registry storage and bandwidth on every push. Fixing both comes down to treating image size and build speed as two distinct engineering targets:
- Smaller images are about what ends up inside the final OCI layers (minimal runtime bases, zero build tools, stripped binaries, production-only dependencies, and
zstdlayer compression). - Faster builds are about what BuildKit can skip, cache, or parallelize (tiny build contexts, cache mounts, decoupled
--linklayers, native$BUILDPLATFORMcompilation, and remote CI cache backends).
New to Dockerfiles? Start with Dockerfile Best Practices and Multi-Stage and Multi-Platform Docker Builds first, then use this post as your full optimization playbook.
The Modern BuildKit Pipeline
Before tweaking individual lines, here is how BuildKit decides what work to run and what to cache:
Part 1: Ways to Make Docker Images Smaller
1. Multi-Stage Builds (Always Strip the Builder)
Compilers, package managers, git, header files, TypeScript compilers, and test runners belong in builder stages—never in the image you ship to production.
- For Go: Compile the binary in
golang:1.27-*, then copy only the single binary intoscratch, Distroless, or a Docker Hardened Image (dhi.io). - For Node.js: Install dev dependencies and compile TypeScript/bundles in a build stage, install production dependencies in an isolated stage (or bundle into a single JS file), and copy only the runtime artifacts into the final stage.
2. Pick the Smallest Safe Runtime Base Image
Base image choice is usually the single biggest size win.
| Base Image | Approximate Base Size | C Library / Shell | Best For (Node.js 26 & Go 1.27) |
|---|---|---|---|
node:26-bookworm / golang:1.27 | 900 MB – 1.1 GB | glibc + full Debian + build tools | Builder stages only (never prod runtime) |
node:26-bookworm-slim | ~220 MB | glibc + minimal Debian | Node apps with prebuilt/native glibc addons |
node:26-alpine | ~130 MB | musl + sh + apk | Small Node services without glibc-only native deps |
dhi.io/node:26 (Docker Hardened) | Ultra-minimal | Stripped shell, non-root default | Hardened Node prod runtimes with minimal CVEs |
gcr.io/distroless/static-debian12:nonroot | ~2 MB | None (no shell, no glibc) | Static Go binaries (CGO_ENABLED=0) |
gcr.io/distroless/cc-debian12:nonroot | ~20 MB | glibc + libgcc (no shell) | Go binaries that require CGO_ENABLED=1 |
scratch | 0 MB | None | Pure static Go binaries (bring your own CA certs/tzdata if needed) |
3. Go-Specific Binary Shrinking
- Static linking (
CGO_ENABLED=0): Eliminateslibcruntime dependencies so your binary runs inscratchordistroless/static-debian12. - Strip debug tables (
-trimpath -ldflags="-s -w"):-trimpathremoves local filesystem paths from the binary (improving reproducibility and slightly shrinking size).-sstrips the symbol table and debug info;-womits DWARF debugging tables. Together they typically cut Go binary size by 25–30%.
- Optional
upxcompression (trade-off):upx --best --lzma /out/servercan shrink a static Go binary another 50–70%, at the cost of a noticeably slower build step and occasional scanner false positives. Skip it unless final artifact size is tightly constrained.
4. Node.js-Specific Size Reductions
- Production-only installs with
--omit=dev: Usenpm ci --omit=dev --ignore-scripts(the modern replacement for deprecated--only=production). Adding--ignore-scriptsalso skips arbitrarypostinstallscripts unless a native addon explicitly needsnpm rebuild <pkg>. - Bundle backend services when possible: If your Node API has pure-JS dependencies, bundling with esbuild or tsup collapses
node_modules(often tens of thousands of tiny files and hundreds of megabytes) into a single minifiedserver.mjsfile—leavingnode_modulesout of the final image altogether. (For Next.js apps,output: 'standalone'traces and copies only required runtime files automatically.) - Drop non-runtime files: Source maps (
*.map), TypeScript sources (src/),README.md, and test fixtures insidenode_modulesordist/should never enter the final stage. - Use
COPY --chowninstead ofRUN chown -R: RunningRUN chown -R node:node /appin a later layer duplicates every file innode_modules(potentially doubling final image size) and wastes build time walking thousands of files. Always set ownership inline withCOPY --link --chown=node:node. - Do not try to shrink
node:26-alpinewithRUN rm -rf: Officialnode:26-*images bundlenpmandnpx, and deleting/usr/local/lib/node_modules/npmin a laterRUNonly writes overlay whiteout entries—the lower base layer still keeps those bytes. If you want a runtime image withoutnpm, start fromdhi.io/node:26orFROM alpinewithapk add --no-cache nodejs(Alpine splitsnodejsandnpminto separate packages).
5. Write a Strict .dockerignore
Without .dockerignore, docker build ships .git, local node_modules, build outputs, logs, and .env files to BuildKit before a single RUN executes—slowing context transfer and risking accidental leaks in COPY . ..
.git
.github
node_modules
dist
build
coverage
*.log
.env*
Dockerfile*
compose*.yaml
README.md
6. Clean Package Caches in the Same Layer (or Never Write Them)
Deleting /var/lib/apt/lists/* in a subsequent RUN instruction does not shrink your image—the previous layer still holds the deleted bytes.
- Best option: Use
RUN --mount=type=cacheso package manager caches live outside image layers completely. - When installing OS packages: Combine install and cleanup in one
RUNusing--no-install-recommends(Debian) or--no-cache(Alpine), and use BuildKit heredocs (RUN <<EOF) instead of fragile&& \chains:
# syntax=docker/dockerfile:1
FROM node:26-bookworm-slim
RUN <<EOF
set -eu
apt-get update
apt-get install -y --no-install-recommends ca-certificates tini
rm -rf /var/lib/apt/lists/*
EOF
7. Switch OCI Compression from gzip to zstd (and Keep Layer Digests Stable)
BuildKit defaults to gzip for layer compression. Exporting with zstd (Zstandard) compresses layers much faster during docker buildx build while yielding smaller registry pushes:
SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) \
docker buildx build \
--output type=image,name=ghcr.io/mythlabs/api:1.0.0,compression=zstd,compression-level=3,force-compression=true,rewrite-timestamp=true \
--push .
Adding SOURCE_DATE_EPOCH + rewrite-timestamp=true normalizes file modification timestamps across layers—so rebuilding identical Go or Node output doesn't generate new layer SHA digests and re-push unchanged layers. (Modern container registries, Docker Engine, and containerd support zstd layers; only fall back to gzip if you must push to legacy infrastructure.)
8. Audit Layer Bloat With dive and buildx
Guessing what made an image 400 MB wastes time. Inspect every layer directly:
# Inspect layer-by-layer filesystem additions and wasted space
dive ghcr.io/mythlabs/api:1.0.0
# Check manifest sizes per architecture without pulling
docker buildx imagetools inspect ghcr.io/mythlabs/api:1.0.0
Part 2: Every Way to Make Docker Builds Faster
1. Order Instructions From Least-Changed to Most-Changed
BuildKit invalidates a layer—and every instruction below it—the moment an input changes. Keep FROM, system packages, and lockfile dependency installs above COPY . . so editing application code never re-installs dependencies.
2. Use BuildKit Cache Mounts (RUN --mount=type=cache)
Even with proper instruction ordering, adding one new package to package-lock.json or go.sum busts the dependency layer and forces npm ci or go mod download to re-fetch every package from the internet.
--mount=type=cache attaches a persistent BuildKit-managed cache directory across builds without writing a single byte of that cache into your final image:
- Go cache mounts: Persist both module downloads (
/go/pkg/mod) and compiled build artifacts (/root/.cache/go-buildviaGOCACHE). In multi-arch builds, isolateGOCACHEper architecture withid=go-build-${TARGETARCH}so concurrentamd64andarm64compiles never thrash each other's object cache. - Node.js cache mounts: Persist
/root/.npmfor npm, or/pnpm/storefor pnpm. If you use pnpm,pnpm fetch --frozen-lockfilereads onlypnpm-lock.yaml(so editingscriptsorversioninpackage.jsonwon't re-download packages), followed bypnpm install --frozen-lockfile --offline. (Note: Node.js 25/26 unbundled Corepack, so installpnpmexplicitly vianpm install -g pnpmor a standalone binary if needed.) - APT cache mounts: If you must
apt-get install, passsharing=locked(--mount=type=cache,target=/var/cache/apt,sharing=locked) and remove/etc/apt/apt.conf.d/docker-clean—withoutsharing=locked, concurrent multi-arch builds crash onapt's lockfile.
3. Decouple Layers With COPY --link
In classic Dockerfiles, COPY --from=builder /out/app /app depends on the parent layer's filesystem state—if the base image updates or an earlier layer changes, downstream COPY layers must be re-created.
Adding --link (supported stably under # syntax=docker/dockerfile:1) turns the COPY into an independent, self-contained layer:
COPY --link --from=builder /out/server /server
This improves cache reuse across base-image updates and lets you rebase onto a patched base image without rebuilding your application layers.
4. Use COPY --exclude, Bind Mounts, and tmpfs
Three modern BuildKit features eliminate unnecessary COPY invalidations and disk I/O:
COPY --exclude: Filter out test files, docs, or configs perCOPYstep without maintaining multiple.dockerignorefiles:dockerfileCOPY --link --exclude=**/*.test.ts --exclude=docs/ . .RUN --mount=type=bind: If a stage only reads files to compile a binary (likego buildornpm run build), bind-mount the build context directly duringRUNinstead of creating an extraCOPYlayer:dockerfileRUN \ CGO_ENABLED=0 go build -o /out/server ./cmd/serverRUN --mount=type=tmpfs,target=/tmp: Mounts/tmpin memory during a build step so scratch compiler/bundler artifacts write at RAM speed and never leak into an image layer.
5. Eliminate QEMU Emulation With $BUILDPLATFORM
Building linux/amd64 + linux/arm64 images on Apple Silicon laptops or x86 CI runners normally relies on QEMU user-space emulation for the non-native architecture—slowing go build and npm run build by 5×–10×.
With FROM --platform=$BUILDPLATFORM, BuildKit runs the compiler natively on your host CPU and cross-compiles for $TARGETOS / $TARGETARCH:
- Go cross-compiles natively out of the box (
GOOS=$TARGETOS GOARCH=$TARGETARCH). - Pure-JS Node builds (
tsc,esbuild,vite,next build) emit platform-independent JavaScript—so you can run the build stage on$BUILDPLATFORMandCOPY --linkthe compiled JS output into the target-architecturenode:26-alpineruntime stage! (Only native C/C++ addons built withnode-gypneed to compile on the target platform.)
6. Structure Stages for Parallel Execution
BuildKit evaluates stages as a directed acyclic graph (DAG). Independent stages run in parallel automatically:
FROM node:26-alpine AS frontend-build
# Builds static assets concurrently
FROM golang:1.27-alpine AS api-build
# Compiles Go binary concurrently
FROM gcr.io/distroless/static-debian12:nonroot AS runtime
COPY --link --from=api-build /out/server /server
COPY --link --from=frontend-build /app/dist /public
Because frontend-build and api-build do not depend on each other, BuildKit builds both at the same time instead of waiting for one to finish.
7. Persist Cache in CI/CD With docker-container + mode=max
Ephemeral CI runners start with an empty local BuildKit cache on every job. To keep builds fast in CI:
- Switch from the default
dockerdriver to thedocker-containerBuildx driver (required for remote cache export andzstdoutput). - Always pass
mode=maxwhen exporting cache so intermediate multi-stage builder layers—not just final runtime layers—are saved:- GitHub Actions:
--cache-from type=gha --cache-to type=gha,mode=max - OCI Registry (ECR, GHCR, GAR):
--cache-from type=registry,ref=ghcr.io/org/app:buildcache --cache-to type=registry,ref=ghcr.io/org/app:buildcache,mode=max
- GitHub Actions:
8. Catch Mistakes in Under a Second With docker build --check
Before spending minutes running a CI build, run BuildKit's native static check (docker build --check ., or add # check=error=true directly under # syntax=docker/dockerfile:1 to fail on warnings):
docker build --check .
Unlike text-only linters, --check evaluates your real build args and context without executing any RUN step—catching casing mismatches (FromAsCasing), secrets leaked via ARG/ENV, shell-form CMD warnings (JSONArgsRecommended), and undefined variables immediately.
Complete Production Examples
Go 1.27: Native Cross-Compiled Multi-Arch + Distroless
# syntax=docker/dockerfile:1
# Run the Go compiler on the host CPU ($BUILDPLATFORM) to avoid slow QEMU emulation
FROM golang:1.27-alpine AS builder
# Set the working directory inside the builder stage
WORKDIR /src
# Copy only dependency manifests first so module downloads stay cached when source changes
COPY go.mod go.sum ./
# Persist the Go module cache across builds without writing it into any image layer
RUN \
go mod download
# Read target OS/architecture injected automatically by Buildx (e.g. linux/amd64, linux/arm64)
ARG TARGETOS TARGETARCH
# Bind-mount source (no extra COPY layer), keep module + per-arch build caches warm,
# disable CGO for a static binary, cross-compile for target arch, and strip debug symbols (-s -w)
RUN \
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
# Minimal ~2 MB runtime base with CA certs & tzdata, no shell, and default non-root user
FROM gcr.io/distroless/static-debian12:nonroot
# Copy only the compiled binary into an independent (--link) layer for fast base-image rebasing
COPY --link --from=builder /out/server /server
# Explicitly enforce the non-root UID/GID
USER nonroot:nonroot
# Document the listening port
EXPOSE 8080
# Run the binary directly in exec form (no shell overhead, clean signal handling)
ENTRYPOINT ["/server"]
Why this is both tiny and fast:
- Final image size is typically ~8–18 MB (
distroless/static~2 MB + stripped Go binary). go buildruns natively on$BUILDPLATFORMwith zero QEMU emulation,bind-mounts source without an extraCOPYlayer, and keeps bothGOMODCACHEandGOCACHEwarm.
Node.js 26 LTS: Multi-Stage Pure-JS Build + Cache Mounts
# syntax=docker/dockerfile:1
# Compile TypeScript/bundles natively on $BUILDPLATFORM (pure JS output is arch-independent)
FROM node:26-alpine AS build
# Set the working directory for the build stage
WORKDIR /app
# Copy lockfiles first so dev/build dependencies stay cached when source files change
COPY package.json package-lock.json ./
# Install all deps cleanly using a persistent npm cache mount, skipping untrusted install scripts
RUN \
npm ci --ignore-scripts
# Copy source into an independent layer while excluding tests and docs from invalidating cache
COPY --link --exclude=**/*.test.ts --exclude=docs/ . .
# Compile the application into dist/
RUN npm run build
# Separate stage for production-only dependencies (BuildKit runs this in parallel with "build")
FROM node:26-alpine AS prod-deps
# Set the working directory for prod dependency installation
WORKDIR /app
# Copy only lockfiles into this stage
COPY package.json package-lock.json ./
# Install only runtime dependencies (--omit=dev) using the shared npm cache mount
RUN \
npm ci --omit=dev --ignore-scripts
# Final lightweight runtime stage (can also swap to dhi.io/node:26 for minimal CVEs)
FROM node:26-alpine AS runner
# Set the runtime working directory
WORKDIR /app
# Mark the container environment as production (using modern KEY=VALUE syntax)
ENV NODE_ENV=production
# Copy prod node_modules as a decoupled layer with inline ownership (avoids RUN chown -R bloat)
COPY --link --from=prod-deps --chown=node:node /app/node_modules ./node_modules
# Copy only compiled output from the build stage with inline ownership
COPY --link --from=build --chown=node:node /app/dist ./dist
# Copy package.json for Node module metadata (e.g. "type": "module")
COPY --link --chown=node:node package.json ./
# Drop root privileges using the built-in non-root "node" user
USER node
# Document the listening port
EXPOSE 3000
# Start Node directly in exec form without a shell wrapper
CMD ["node", "dist/server.js"]
Why this works so well:
buildandprod-depsrun in parallel under BuildKit, both sharing the persistent/root/.npmcache mount.- If your Node service has zero native
node-gypdependencies and you bundledist/server.mjswithesbuildortsup, you can delete theprod-depsstage completely and shrink the final image even further (or swap therunnerbase todhi.io/node:26for minimal CVEs).
GitHub Actions: Remote Cache + zstd Multi-Arch Push
name: Build and Push Image
on:
push:
branches: [main] # Trigger on pushes to the main branch
jobs:
docker:
runs-on: ubuntu-latest # Standard GitHub-hosted runner
permissions:
contents: read # Allow checking out repository code
packages: write # Allow pushing images to GHCR
steps:
- uses: actions/checkout@v4 # Fetch repo source
# Register QEMU binfmt handlers (only needed if a stage compiles native code on non-host arch)
- uses: docker/setup-qemu-action@v3
# Create a Buildx builder using the "docker-container" driver (required for gha cache & zstd)
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3 # Authenticate to GitHub Container Registry
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6 # Build multi-arch image and push with remote cache
with:
context: . # Use repository root as build context (filtered by .dockerignore)
platforms: linux/amd64,linux/arm64 # Produce multi-architecture manifest list
push: true # Push image directly from BuildKit to GHCR
tags: ghcr.io/${{ github.repository }}:${{ github.sha }} # Tag with immutable commit SHA
cache-from: type=gha # Pull prior BuildKit layer cache from GitHub Actions cache
cache-to: type=gha,mode=max # Save all builder + runtime layers (not just final stage)
outputs: type=image,compression=zstd,compression-level=3,force-compression=true # Fast, compact zstd layers
Summary: The 80/20 Checklist
If you only have 10 minutes to optimize an existing Go or Node Docker build, start here:
- Add
.dockerignoreso.git, localnode_modules, and logs stay out of the build context. - Use
# syntax=docker/dockerfile:1+ multi-stage builds targetingdistroless/static-debian12:nonroot(Go) ornode:26-alpine/dhi.io/node:26(Node). - Add
RUN --mount=type=cachefor/go/pkg/mod,/root/.cache/go-build, and/root/.npm, plusCOPY --linkin runtime stages. - Compile on
$BUILDPLATFORMand export CI cache withmode=max+zstdso multi-arch builds stay fast end to end.
Continue reading
A practical walkthrough of multi-stage and multi-platform Docker builds for developers looking to shrink image sizes and ship across CPU architectures.
In this exploration, delve into Dockerfile best practices—essential guidelines that empower you to build containers that are not only robust but also optimized for performance and security. These best practices will pave the way for a smoother and more effective containerized development process.