What actually makes a Node.js Docker image large?

A Node.js image is a stack of layers, and each one adds to the total: the base OS filesystem, the Node runtime, node_modules, and whatever the build left behind. Teams often focus on the first layer, but the later ones are usually larger and easier to shrink.

node_modules grows quickly because npm install pulls in devDependencies such as test runners, bundlers, type definitions and linters, plus their transitive dependencies. Native modules can also pull in compilers, Python and headers if the build toolchain is installed in the same image. Build output and the npm cache (typically under the user's home directory) add more. Because layers are additive, deleting files in a later RUN step does not reclaim space that an earlier layer already committed.

Measure before you change the base image. docker image ls shows the total size of each image. docker history <image> lists each layer with its size and the instruction that created it, so you can see which COPY or RUN step is responsible for most of the size.

Illustrative estimate. The sizes below are assumed inputs, not measurements:

Component Unpruned (MB) Pruned (MB)
Base OS layer 75 75
Node runtime 100 100
node_modules 400 (with devDependencies) 120 (production only)
npm cache + build artifacts 60 0
Total 635 295

In this example, pruning saves 340 MB. Replacing the assumed 75 MB base with an 8 MB one would save about 67 MB. Fix dependency hygiene first, then choose the base image.

docker build -t myapp:baseline .

docker image ls myapp

docker history --no-trunc myapp:baseline

docker history --format '{{.Size}}\t{{.CreatedBy}}' myapp:baseline

docker build -t myapp:pruned .
docker image ls myapp

Uses docker image ls for total image size and docker history for per-layer sizes, so you can see which step dominates before and after pruning dependencies.

How do multi-stage builds reduce image size?

A multi-stage build is the mechanism that does the pruning. A Dockerfile can define several FROM stages, and only the last one becomes the shipped image. Earlier stages exist only during the build. Their layers are not part of the final image unless you explicitly copy files out of them.

The builder stage is where the heavy work happens. It starts from a full Node.js image that includes npm and, when native modules need compiling, Python, make, and a C/C++ toolchain. It installs every dependency, devDependencies included, so TypeScript, bundlers, and test tooling can run. After the build, it removes dev packages with a production-only install such as npm ci --omit=dev, or with npm prune --omit=dev.

The runtime stage starts from a minimal base and uses COPY --from=builder to pull in exactly three things: the compiled output (for example dist/), the pruned node_modules, and package.json. The flow is one-way. Toolchain, npm cache, source files, and devDependencies stay in the builder and are discarded.

This usually saves more than changing the base image because dependencies and build tooling tend to outweigh the operating system layer, as the previous example showed. Switching from Debian to Alpine or distroless means retesting native modules, rewriting health checks, and changing debugging workflows, often for tens of megabytes. Adding a second stage is a local change to one Dockerfile and captures most of the reduction. Do it first, then decide whether a base-image migration still pays for itself.

+------------------------------------------------------------+
| STAGE 1: builder   (FROM full Node.js image)               |
|                                                            |
|  npm + npm cache    Python, make, C/C++ toolchain          |
|  source files       devDependencies (TS, bundler, tests)   |
|                                                            |
|  npm ci  -->  npm run build  -->  npm prune --omit=dev     |
|                                                            |
|  out:   dist/        node_modules (prod)    package.json   |
+------------------------------------------------------------+
          |                   |                    |
          |                   |                    |  COPY --from=builder
          |                   |                    |  (one-way, 3 items)
          v                   v                    v
+------------------------------------------------------------+
| STAGE 2: runtime   (FROM minimal base)  = shipped image    |
|                                                            |
|  in:    dist/        node_modules (prod)    package.json   |
|                                                            |
+------------------------------------------------------------+

  Left behind in builder (never in the final image):
  +----------------------------------------------------------+
  | toolchain | npm cache | source files | devDependencies   |
  +----------------------------------------------------------+

The builder stage holds npm, the native toolchain, source, and devDependencies, while the runtime stage receives only dist/, the pruned production node_modules, and package.json through COPY --from=builder, and everything else is discarded with the builder.

What are Alpine and distroless images, and how do they differ?

Alpine is a complete general-purpose Linux distribution designed to be small. It uses musl libc instead of glibc and BusyBox instead of GNU coreutils, so a single binary supplies sh, ls, wget, and dozens of other tools. The apk package manager also ships in the image, which means you can install packages during a build, or inside a running container, the same way you would on a VM. The official Node.js Alpine images add the Node runtime to that base and run as root unless you change the user.

Distroless images are not a distribution in that sense. They are assembled from Debian packages but contain only what a runtime needs: glibc, CA certificates, timezone data, and, in the Node.js variant, the node binary. They include no shell, no package manager, and no coreutils. Most teams use the nonroot tag, which sets a non-root user by default. Because there is nothing to execute except node, the entrypoint must call it directly, and anything else the image needs must be copied in from a build stage.

Aspect Alpine Distroless
libc musl glibc (Debian)
Shell BusyBox sh None
Package manager apk, available at runtime None
Default user root non-root on nonroot tags
Adding system files apk add in the Dockerfile COPY from a builder stage
Security patches Alpine maintainers, via apk Debian security updates, picked up when the distroless images are rebuilt and you pull the new image

How does a minimal Node.js image work at runtime?

A container image is not a virtual machine. It is a set of filesystem layers plus metadata such as the entrypoint, default command, user, working directory and environment variables. When a container starts, the runtime stacks the layers into one root filesystem, applies that metadata, and executes the entrypoint as the container's first process. The host kernel is shared. Nothing in the image boots, and no init system or service manager runs unless you put one there.

For a Node.js service, that first process is the node binary. To run, it needs three things from the image:

  • The dynamic loader and C library. node is a dynamically linked executable. The kernel hands it to the loader named in the binary, which then resolves the shared libraries it depends on. On Alpine that is musl's loader. On Debian-based images, including distroless, it is glibc's. This is why the libc of the builder and the runtime must match.
  • The supporting shared libraries. Node also links against the C++ runtime and a few other system libraries. Alpine and Debian-based Node images supply them as packages. The distroless Node.js image ships them as part of the image.
  • Data files the process reads. CA certificates for outbound TLS, timezone data, and /etc/passwd entries for the configured user.

Everything else in a general-purpose image, such as a shell, coreutils and a package manager, is there for people and build scripts, not for the running process. Alpine keeps a small set of those tools. Distroless removes them entirely. That is how both images get small: they keep the runtime dependencies of node and drop the rest.

One consequence of running node directly as the first process is that it becomes PID 1. The kernel does not apply default signal actions to PID 1, so a Node process that does not register a SIGTERM handler will not exit on docker stop and is killed after the grace period instead. Handle SIGTERM in the application and close servers cleanly, or run the container with an init process such as the one Docker adds with docker run --init. This applies to Alpine and distroless alike. On distroless you cannot work around it with a shell wrapper script, because there is no shell.

Why does musl vs glibc matter for Node.js native modules?

Native addons are compiled .node shared libraries, and they link against the C library of the system they were built on. Most prebuilt binaries published to npm target glibc. On Alpine, which uses musl, a glibc-built addon typically fails at require() time with an error about a missing loader such as ld-linux-x86-64.so.2 or unresolved symbols. Some packages publish separate musl prebuilds, often tagged linuxmusl. When none exists, the install falls back to compiling from source with node-gyp. That means adding Python, make, and a C++ compiler to the builder stage, which lengthens builds and makes them depend on toolchain versions. Distroless Node images are Debian-based and use glibc, so the standard prebuilds load as published.

The less obvious problems are behavioral, and they pass local testing because developer machines run macOS or a glibc distribution:

  • DNS resolution. musl's resolver sends queries to all configured nameservers in parallel. It ignores some resolv.conf options that glibc honors. Older musl releases also did not retry over TCP when a UDP response was truncated. Lookups that work on a laptop can fail or behave differently inside a Kubernetes pod with large DNS responses or a custom search domain setup.
  • Memory allocation. V8 manages the JavaScript heap itself, but Buffers, the libuv threadpool, and native addons call malloc. musl's allocator favors low memory overhead over multithreaded throughput, so allocation-heavy native workloads such as image processing or compression can run slower than they do on glibc.

To check whether your dependency tree has native code, search node_modules for .node files and binding.gyp files after a clean install. Also review which packages run install scripts. Then run your test suite inside the target image, not only on the host.

#!/usr/bin/env bash
set -euo pipefail

echo "== Compiled addons (.node files) =="
find node_modules -type f -name '*.node' -print

echo "== libc each addon links against =="
find node_modules -type f -name '*.node' -print0 |
  while IFS= read -r -d '' f; do
    echo "$f: $(readelf -d "$f" | grep -o 'libc[^]]*' | tr '\n' ' ')"
  done

echo "== Packages with binding.gyp (npm builds these with node-gyp) =="
find node_modules -type f -name binding.gyp -print

echo "== Packages that declare install-time scripts =="
find node_modules -type f -name package.json -print0 | xargs -0 node -e '
  const path = require("path");
  for (const f of process.argv.slice(1)) {
    let p;
    try { p = require(path.resolve(f)); } catch { continue; }
    if (!p.name) continue; // skip nested non-package manifests
    const s = p.scripts || {};
    const hooks = ["preinstall", "install", "postinstall"].filter(k => s[k]);
    if (hooks.length || p.gypfile) {
      console.log(`${p.name}: ${hooks.map(k => `${k}=${s[k]}`).join("; ") || "gypfile"}`);
    }
  }'

docker run --rm -v "$PWD":/src:ro node:20-alpine sh -c \
  'cp -r /src /app && cd /app && rm -rf node_modules && npm ci && npm test'

A shell audit that lists compiled .node addons and the libc each one links against, flags packages that build with node-gyp or run install scripts, and then reinstalls and tests the project inside an Alpine container so musl-specific failures show up before deployment.

How do you write a multi-stage Dockerfile for Alpine and for distroless?

Both builds follow the same pattern. The builder installs dependencies and compiles native addons. The runtime stage receives only the files the process needs at run time. The builder must use the same libc as the runtime. That is because npm ci compiles native addons, or downloads prebuilt binaries, for the libc it detects at install time.

Alpine. Use a node:<version>-alpine image for both stages. In the builder, run npm ci --omit=dev. If a package has no musl prebuild, add python3, make and g++ with apk add in the builder only. In the runtime stage, copy node_modules, package.json and your built application directory. Switch to the bundled node user with USER node. Start with CMD ["node", "server.js"].

Distroless. Build on a Debian-based Node image, such as a bookworm-slim variant. Its Debian release should match the one the distroless image is built on. Run the same npm ci --omit=dev. Then copy the artifacts into a distroless Node.js image. Use its nonroot tag, or set USER nonroot. The distroless Node.js image already sets node as its entrypoint, so the command takes only the script, in exec form: CMD ["server.js"]. A shell-form command fails because the image has no /bin/sh.

Mixing builder and runtime libcs breaks native modules. A .node file built against glibc links to glibc's dynamic loader and symbols. On musl the require call fails with a loader or "symbol not found" error. The reverse fails the same way.

Distroless base images already include CA certificates. To add an internal CA, install it in the builder with update-ca-certificates. Then copy /etc/ssl/certs/ca-certificates.crt into the runtime at the same path. A missing shared library works the same way: copy the exact .so files from the builder into identical paths. Check what an addon needs by running ldd on its .node file in the builder.

FROM node:22-bookworm-slim AS build
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src/ ./src/

RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \
 && rm -rf /var/lib/apt/lists/*
COPY certs/internal-root-ca.crt /usr/local/share/ca-certificates/
RUN update-ca-certificates

FROM gcr.io/distroless/nodejs22-debian12:nonroot
WORKDIR /app

COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/package.json ./
COPY --from=build /app/src ./src

COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
ENV NODE_ENV=production \
    NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt

CMD ["src/server.js"]

A multi-stage Dockerfile that installs production dependencies in a Debian 12 glibc builder. It copies only node_modules, the app code and an updated CA bundle into a matching distroless Node runtime, which runs as non-root with an exec-form CMD.

How do you debug and secure a container with no shell?

On distroless, docker exec -it <container> sh fails because there is no shell binary to start. The usual workaround is an ephemeral debug container. In Kubernetes, kubectl debug with --target attaches a tooling image to the running pod and shares its process namespace. From there you can inspect /proc/<pid>/root to see the app's filesystem. Some teams also keep a debug variant of the base image that includes a busybox shell, and deploy it only when they need to investigate. Both approaches work, but each needs RBAC rules, a pre-approved tooling image, and a runbook that on-call engineers have practiced. Without that preparation, an incident at 3 a.m. is the wrong time to learn the process.

Alpine is easier to debug: sh and apk add are available immediately. An attacker who gains code execution gets the same tools: a shell, wget, and a package manager to install more. If you ship Alpine, remove apk and unneeded binaries in the final stage, run as a non-root user, and use a read-only root filesystem.

Fewer packages mean fewer CVE findings and less tooling available after a compromise. A near-zero scanner count also depends on what the scanner can identify. Scanners match packages against database metadata, so files copied in without that metadata, such as vendored binaries or the Node runtime itself, can be missed. A low count is not proof the image is secure.

The ongoing cost is maintenance:

  • Pin by digest. Builds stay reproducible, because a tag can be repointed to a different image while a digest cannot.
  • Rebuild on a schedule. Without regular rebuilds, a pinned digest never picks up base-image patches.
  • Automate the process. Use automated digest-bump pull requests and rescans so that patching does not depend on someone remembering to do it.

How can minimal images save engineering time?

The time savings come from work that scales with the number of packages in an image and the number of times the image moves. They are real but not automatic, and a migration can cost more time than it saves if native modules or debugging workflows are not ready.

Where time is saved:

  • Vulnerability triage. Every package in the base is something a scanner can flag, and every finding needs someone to decide whether it is exploitable, whether a fix exists, and whether to rebuild. Removing a shell, coreutils and a package manager removes the findings attached to them. This is usually the largest recurring saving, because triage is manual and repeats across every service that shares the base.
  • Image transfer. Smaller images push to the registry and pull to nodes faster. That shortens CI pipelines that build and push on every commit, and shortens the delay before a new pod can start on a node that does not have the image cached, which matters during autoscaling and node replacement.
  • Fewer accidental dependencies. When the runtime image has no shell or package manager, nobody can add a startup script that calls curl, or patch a running container by hand. Behavior is defined entirely by the Dockerfile, which makes failures easier to reproduce.
  • Shared base images. A platform team that standardizes one or two pruned bases, rebuilt on a schedule, patches once and lets every service pick up the change with a digest bump.

Where time is spent instead:

  • Retesting and possibly rebuilding native addons when moving to musl.
  • Rewriting shell-form CMD, entrypoint scripts and shell-based health checks for distroless.
  • Setting up and practicing the ephemeral-container debugging workflow.

Illustrative estimate. All inputs below are assumed, not measured. Assume a team runs 20 services on a shared base. Assume the full base produces 15 scanner findings per service per month that need a look, a minimal base produces 3, and each finding takes 10 minutes to triage. That is 20 × 12 × 10 = 2,400 minutes, or about 40 engineer-hours per month avoided. Against that, assume the migration takes 4 hours per service, or 80 hours total, plus 8 hours to build a debugging runbook. Under these assumptions the migration pays back in a little over two months. If your services have fewer findings, many native modules, or triage is already automated, the payback period is longer, and it may never arrive. Run the same calculation with your own scanner output and incident history before committing.

Multi-stage builds and dependency pruning give most of the transfer-time savings at very little migration cost, which is another reason to do them before changing the base.

Who should use distroless or Alpine Node images?

Distroless fits:

  • Teams running Node.js services in production on Kubernetes or a similar orchestrator, where ephemeral debug containers are available and on-call engineers already use them.
  • Services whose dependencies are pure JavaScript or ship glibc prebuilds, so the Debian-based distroless image runs them unchanged.
  • Organizations with strict attack-surface or compliance requirements, where reducing scanner findings and removing interactive tooling from production is an explicit goal.
  • Platform teams that maintain shared base images and can own the pinning, rebuild and rescan process.

Alpine fits:

  • Teams that want a small image but still need a shell and apk in the container, for example for entrypoint scripts or hands-on debugging.
  • Services whose native dependencies publish musl prebuilds, or whose test suites already run inside Alpine in CI.
  • Utility containers, sidecars and CI job images, where image size matters and shell access is useful.

Neither is the right first choice for:

  • Local development images, where a full toolchain and shell are what developers need.
  • Services with native addons that lack musl builds (Alpine) or that need system packages you cannot easily copy in (distroless). A Debian slim image is simpler.
  • Teams without a defined debugging workflow for shell-less containers. Adopt distroless after that workflow exists, not before.

When should you choose distroless, Alpine, or a slim Debian image?

Work through these questions in order. The first one that forces a constraint usually settles the choice.

  1. Do you ship native addons or glibc-only binaries? If a dependency has no musl prebuild, Alpine means compiling from source in CI or debugging subtle runtime differences. Prefer a glibc base.
  2. Does anyone need a shell in the running container? If on-call engineers expect to exec in, distroless takes that away. That is fine only if ephemeral debug containers or rich logs already cover it.
  3. How does your team debug today? Teams without ephemeral-container tooling pay for distroless in incident time, not in build time.
  4. Who patches the base, and how often? Pick a base whose maintainers publish fixes quickly, and whose provenance you can verify. Then commit to rebuilding on that cadence.
  5. What do your scanners require? Some scanners report less detail on minimal images, or flag Alpine packages differently. Confirm that your tooling reads the base you choose.
Base Choose when Avoid when Engineering cost
Distroless Pure-JS or glibc-compatible deps, mature debug tooling, strict attack-surface goals Team relies on shell access Upfront: debug workflow, entrypoint rewrites
Alpine Small images with a shell, deps known to work on musl Native addons without musl builds Ongoing: musl-specific build and runtime issues
Debian slim Native modules, mixed teams, fastest path to production Size or package count is a hard requirement Lowest: larger image, more packages to patch

Debian-based slim Node images are the default to beat. They keep glibc and a shell, and drop most of the full image's tooling. Move to distroless only when the reduction in attack surface justifies the change to your debugging workflow.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to distroless vs alpine node, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.