Amit.Brews.Code
BlogAbout
mailgithublinkedinRSS
Amit Bisht
•
© 2026
•
Amit.Brews.Code
Published on
Friday, December 4, 2026
16 min read

Smaller and Faster Docker Images: The Complete Node.js and Go Guide

Authors
  • Amit Bisht
    Name
    Amit Bisht
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
    • Go 1.27: Native Cross-Compiled Multi-Arch + Distroless
    • Node.js 26 LTS: Multi-Stage Pure-JS Build + Cache Mounts
    • GitHub Actions: Remote Cache + zstd Multi-Arch Push
  • 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 zstd layer compression).
  • Faster builds are about what BuildKit can skip, cache, or parallelize (tiny build contexts, cache mounts, decoupled --link layers, native $BUILDPLATFORM compilation, 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:

Modern BuildKit Build and Cache Flow
Rendering diagram…

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 into scratch, 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 ImageApproximate Base SizeC Library / ShellBest For (Node.js 26 & Go 1.27)
node:26-bookworm / golang:1.27900 MB – 1.1 GBglibc + full Debian + build toolsBuilder stages only (never prod runtime)
node:26-bookworm-slim~220 MBglibc + minimal DebianNode apps with prebuilt/native glibc addons
node:26-alpine~130 MBmusl + sh + apkSmall Node services without glibc-only native deps
dhi.io/node:26 (Docker Hardened)Ultra-minimalStripped shell, non-root defaultHardened Node prod runtimes with minimal CVEs
gcr.io/distroless/static-debian12:nonroot~2 MBNone (no shell, no glibc)Static Go binaries (CGO_ENABLED=0)
gcr.io/distroless/cc-debian12:nonroot~20 MBglibc + libgcc (no shell)Go binaries that require CGO_ENABLED=1
scratch0 MBNonePure static Go binaries (bring your own CA certs/tzdata if needed)
Watch out for Alpine musl & scratch CA certs

Two common gotchas when shrinking bases:

  1. scratch has no root CA certificates or timezone data. If your Go service makes HTTPS calls, copy /etc/ssl/certs/ca-certificates.crt from the builder (or import time/tzdata / golang.org/x/crypto/x509roots/fallback)—or use gcr.io/distroless/static-debian12:nonroot, which includes CA certs and tzdata in ~2 MB.
  2. Alpine uses musl libc. Native Node addons compiled against glibc or heavy DNS-heavy workloads can behave differently under musl; use -bookworm-slim when compatibility matters.

3. Go-Specific Binary Shrinking#

  1. Static linking (CGO_ENABLED=0): Eliminates libc runtime dependencies so your binary runs in scratch or distroless/static-debian12.
  2. Strip debug tables (-trimpath -ldflags="-s -w"):
    • -trimpath removes local filesystem paths from the binary (improving reproducibility and slightly shrinking size).
    • -s strips the symbol table and debug info; -w omits DWARF debugging tables. Together they typically cut Go binary size by 25–30%.
  3. Optional upx compression (trade-off): upx --best --lzma /out/server can 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#

  1. Production-only installs with --omit=dev: Use npm ci --omit=dev --ignore-scripts (the modern replacement for deprecated --only=production). Adding --ignore-scripts also skips arbitrary postinstall scripts unless a native addon explicitly needs npm rebuild <pkg>.
  2. 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 minified server.mjs file—leaving node_modules out of the final image altogether. (For Next.js apps, output: 'standalone' traces and copies only required runtime files automatically.)
  3. Drop non-runtime files: Source maps (*.map), TypeScript sources (src/), README.md, and test fixtures inside node_modules or dist/ should never enter the final stage.
  4. Use COPY --chown instead of RUN chown -R: Running RUN chown -R node:node /app in a later layer duplicates every file in node_modules (potentially doubling final image size) and wastes build time walking thousands of files. Always set ownership inline with COPY --link --chown=node:node.
  5. Do not try to shrink node:26-alpine with RUN rm -rf: Official node:26-* images bundle npm and npx, and deleting /usr/local/lib/node_modules/npm in a later RUN only writes overlay whiteout entries—the lower base layer still keeps those bytes. If you want a runtime image without npm, start from dhi.io/node:26 or FROM alpine with apk add --no-cache nodejs (Alpine splits nodejs and npm into 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 . ..

.dockerignore
.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=cache so package manager caches live outside image layers completely.
  • When installing OS packages: Combine install and cleanup in one RUN using --no-install-recommends (Debian) or --no-cache (Alpine), and use BuildKit heredocs (RUN <<EOF) instead of fragile && \ chains:
dockerfile
# 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:

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

bash
# 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-build via GOCACHE). In multi-arch builds, isolate GOCACHE per architecture with id=go-build-${TARGETARCH} so concurrent amd64 and arm64 compiles never thrash each other's object cache.
  • Node.js cache mounts: Persist /root/.npm for npm, or /pnpm/store for pnpm. If you use pnpm, pnpm fetch --frozen-lockfile reads only pnpm-lock.yaml (so editing scripts or version in package.json won't re-download packages), followed by pnpm install --frozen-lockfile --offline. (Note: Node.js 25/26 unbundled Corepack, so install pnpm explicitly via npm install -g pnpm or a standalone binary if needed.)
  • APT cache mounts: If you must apt-get install, pass sharing=locked (--mount=type=cache,target=/var/cache/apt,sharing=locked) and remove /etc/apt/apt.conf.d/docker-clean—without sharing=locked, concurrent multi-arch builds crash on apt's lockfile.
Cache mounts do not travel in type=gha or type=registry

BuildKit's remote caches (--cache-to type=gha,mode=max or type=registry,mode=max) export image layers, not --mount=type=cache volumes. On ephemeral CI runners (ubuntu-latest), a cache hit still skips unchanged install layers via mode=max, but when a lockfile changes, --mount=type=cache starts empty unless you run a persistent/remote BuildKit builder (--driver remote), a persistent self-hosted runner, or extract/restore the mount with buildkit-cache-dance. Even on ephemeral runners, keeping --mount=type=cache keeps caches out of your image layers and speeds up local builds.


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:

dockerfile
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 per COPY step without maintaining multiple .dockerignore files:
    dockerfile
    COPY --link --exclude=**/*.test.ts --exclude=docs/ . .
    
  • RUN --mount=type=bind: If a stage only reads files to compile a binary (like go build or npm run build), bind-mount the build context directly during RUN instead of creating an extra COPY layer:
    dockerfile
    RUN --mount=type=bind,target=. \
        --mount=type=cache,target=/go/pkg/mod \
        --mount=type=cache,id=go-build-${TARGETARCH},target=/root/.cache/go-build \
        CGO_ENABLED=0 go build -o /out/server ./cmd/server
    
  • RUN --mount=type=tmpfs,target=/tmp: Mounts /tmp in 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 $BUILDPLATFORM and COPY --link the compiled JS output into the target-architecture node:26-alpine runtime stage! (Only native C/C++ addons built with node-gyp need 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:

dockerfile
FROM --platform=$BUILDPLATFORM node:26-alpine AS frontend-build
# Builds static assets concurrently

FROM --platform=$BUILDPLATFORM 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:

  1. Switch from the default docker driver to the docker-container Buildx driver (required for remote cache export and zstd output).
  2. Always pass mode=max when 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
Do not forget mode=max

The default cache export mode (mode=min) only exports layers belonging to the final image stage. For multi-stage Go and Node builds, that drops your entire builder dependency cache unless you set mode=max.


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

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

Dockerfile.godockerfile
# syntax=docker/dockerfile:1

# Run the Go compiler on the host CPU ($BUILDPLATFORM) to avoid slow QEMU emulation
FROM --platform=$BUILDPLATFORM 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 --mount=type=cache,target=/go/pkg/mod \
    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 --mount=type=bind,target=. \
    --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,id=go-build-${TARGETARCH},target=/root/.cache/go-build \
    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 build runs natively on $BUILDPLATFORM with zero QEMU emulation, bind-mounts source without an extra COPY layer, and keeps both GOMODCACHE and GOCACHE warm.

Node.js 26 LTS: Multi-Stage Pure-JS Build + Cache Mounts#

Dockerfile.nodedockerfile
# syntax=docker/dockerfile:1

# Compile TypeScript/bundles natively on $BUILDPLATFORM (pure JS output is arch-independent)
FROM --platform=$BUILDPLATFORM 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 --mount=type=cache,target=/root/.npm \
    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 --mount=type=cache,target=/root/.npm \
    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:

  • build and prod-deps run in parallel under BuildKit, both sharing the persistent /root/.npm cache mount.
  • If your Node service has zero native node-gyp dependencies and you bundle dist/server.mjs with esbuild or tsup, you can delete the prod-deps stage completely and shrink the final image even further (or swap the runner base to dhi.io/node:26 for minimal CVEs).

GitHub Actions: Remote Cache + zstd Multi-Arch Push#

.github/workflows/docker.ymlyaml
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:

  1. Add .dockerignore so .git, local node_modules, and logs stay out of the build context.
  2. Use # syntax=docker/dockerfile:1 + multi-stage builds targeting distroless/static-debian12:nonroot (Go) or node:26-alpine / dhi.io/node:26 (Node).
  3. Add RUN --mount=type=cache for /go/pkg/mod, /root/.cache/go-build, and /root/.npm, plus COPY --link in runtime stages.
  4. Compile on $BUILDPLATFORM and export CI cache with mode=max + zstd so multi-arch builds stay fast end to end.
View on GitHub
End of article · 16 min read

Continue reading

Docker
Multi stage and multi platform docker build

A practical walkthrough of multi-stage and multi-platform Docker builds for developers looking to shrink image sizes and ship across CPU architectures.

4 min read→
Docker
Dockerfile Best Practices

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.

8 min read→

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
  • Go 1.27: Native Cross-Compiled Multi-Arch + Distroless
  • Node.js 26 LTS: Multi-Stage Pure-JS Build + Cache Mounts
  • GitHub Actions: Remote Cache + zstd Multi-Arch Push
  • Summary: The 80/20 Checklist

Tags

DockerGo

Previous Article

HTTP Caching Headers Explained

Related

  • Multi stage and multi platform docker build
  • Dockerfile Best Practices
  • Quality Docker Starters With Docker init
← Back to the blog