What are distroless and Alpine base images, and how do they differ for Node?
Alpine is a small, general-purpose Linux distribution built on musl libc and BusyBox. It includes a shell, standard utilities, and the apk package manager, so it behaves like a normal distro with fewer packages. The official Node images publish Alpine variants.
Distroless images come from Google's distroless project. They contain the Node runtime, the shared libraries it needs, CA certificates, and timezone data on a Debian/glibc base. There is no shell and no package manager. You build the application in another stage and copy only the output into the final image.
Teams use either option to ship fewer packages. Fewer packages means a smaller download, faster pulls on new nodes, and fewer components for a vulnerability scanner to report. The two options get there differently. Alpine keeps a usable OS but swaps the C library. Distroless keeps glibc but removes the OS tooling.
A third option is the -slim Debian variant of the official Node image. It is a trimmed Debian with glibc, a shell, and apt. It is larger than the other two but has the fewest compatibility surprises.
| Aspect | Alpine | Distroless | Slim Debian |
|---|---|---|---|
| libc | musl | glibc | glibc |
| Shell | BusyBox sh |
None (:debug tags add BusyBox) |
bash |
| Package manager | apk |
None | apt |
| Debugging in place | exec a shell |
Debug tag or ephemeral container | exec a shell |
| Non-root | Built-in node user |
:nonroot tags |
Built-in node user |
| Adding OS packages | apk add |
Copy files from a builder stage | apt-get install |
Where does Docker image size really come from in a Node service?
Base image choice gets most of the attention, but the larger share of a typical Node image usually comes from what your build leaves behind. Common culprits are a full node_modules that still contains dev dependencies, the npm or Yarn cache, TypeScript sources next to the compiled output, test fixtures, and the .git directory when it isn't excluded by .dockerignore. These can easily exceed the size gap between two base images. The Node runtime binary is also present in every variant, so no base image removes that cost.
Measure before you change anything. docker image ls reports the total local size of each tag. docker history <image> lists every layer with its size and the instruction that created it, so you can see which COPY or RUN step added the weight. A single COPY . . layer that is larger than the base layers tells you to fix the build stage first.
Illustrative estimate. Assume these inputs: a base layer of about 50 MB for Alpine and about 60 MB for a distroless Node image, plus a single-stage build that copies 300 MB of node_modules (including dev tooling) and 40 MB of source and cache. In that case the base difference is roughly 3% of a 400 MB image. Pruning to production dependencies and copying only build output into the final stage could remove most of the 340 MB.
Order the work accordingly. Switching base images involves libc compatibility testing and changes to how you debug. Cleaning up the final stage takes less effort and usually saves far more space.
#!/usr/bin/env bash
# Measure where image size actually comes from before touching the base image.
# Usage: ./measure.sh my-service:alpine my-service:distroless
set -euo pipefail
for image in "$@"; do
echo "== ${image} =="
# Total local size of the tag, as reported by Docker.
docker image ls --format '{{.Repository}}:{{.Tag}} {{.Size}}' "${image}"
# Per-layer breakdown. --human=false prints sizes in bytes so the output
# can be sorted numerically. The largest layers appear first, together
# with the instruction that created them.
echo "Largest layers (bytes, instruction):"
docker history --no-trunc --human=false \
--format '{{.Size}}\t{{.CreatedBy}}' "${image}" \
| sort -rn \
| head -n 5 \
| cut -c1-140 # trim long RUN lines for readability
echo
done
# Reading the output:
# - If a COPY . . or npm install/ci layer is larger than the base layers,
# fix the build stage first: prune dev dependencies, clear the package
# cache, and copy only build output into the final stage.
# - Compare the base layers of the two tags only after that is done.
A small script that prints each image's total size and its five largest layers with the instructions that created them, so you can tell whether build output or the base image is driving size.
How do you build a multi-stage Dockerfile for a Node API?
The builder stage uses a full Node image. It runs npm ci against the lockfile, compiles TypeScript or bundles, and then runs npm prune --omit=dev so that only production dependencies remain in node_modules. Running the prune after the build matters because the compiler and type packages are needed until the build finishes. The runtime stage copies three things from the builder: node_modules, the build output directory, and package.json. Everything else stays behind, including source, tests, and the npm cache.
Alpine runtime
The official Node Alpine image already includes an unprivileged node user, so USER node works with no extra setup. If your platform requires a specific UID, create one with addgroup and adduser in a RUN step. Copy files with COPY --chown=node:node. Without it, the files belong to root. The app can still read them, but any write to a cache or upload directory fails with a permission error at runtime, not at build time.
Distroless runtime
Use the nonroot tag variant, which runs as UID 65532. The image has no shell, so you cannot run chown or adduser in this stage. COPY --chown=nonroot:nonroot (or the numeric ID) is the only way to set ownership. The image's entrypoint is already node, so CMD takes just the script path, such as dist/server.js.
Tags versus digests
Pinning FROM by digest makes builds byte-for-byte reproducible. The tradeoff is that you then need an update process, such as an automated PR that bumps the digest, or security patches never arrive. A floating tag picks up patches on every rebuild, but it can also bring in an unreviewed behavior change in the middle of an unrelated deploy.
# Match the builder's libc to the runtime so native addons work:
# distroless: docker build --target runtime-distroless .
# alpine: docker build --build-arg BUILD_BASE=node:22-alpine --target runtime-alpine .
ARG BUILD_BASE=node:22-bookworm
FROM ${BUILD_BASE} AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci # dev deps needed for compilation
COPY . .
RUN npm run build && npm prune --omit=dev # prune only after the build
# Floating tag: picks up patches on rebuild, may change behavior.
# For reproducibility pin a digest instead and bump it via an automated PR:
# FROM node:22-alpine@sha256:<digest>
FROM node:22-alpine AS runtime-alpine
ENV NODE_ENV=production
WORKDIR /app
# Writable dir must belong to the runtime user, or writes fail at runtime
RUN mkdir -p /app/uploads && chown node:node /app/uploads
COPY --chown=node:node --from=builder /app/node_modules ./node_modules
COPY --chown=node:node --from=builder /app/dist ./dist
COPY --chown=node:node --from=builder /app/package.json ./
USER node
CMD ["node", "dist/server.js"]
# Debian 12 base matches the default bookworm builder; :nonroot runs as UID 65532
FROM gcr.io/distroless/nodejs22-debian12:nonroot AS runtime-distroless
ENV NODE_ENV=production
WORKDIR /app
# No shell here, so COPY --chown is the only way to set ownership
COPY --chown=65532:65532 --from=builder /app/node_modules ./node_modules
COPY --chown=65532:65532 --from=builder /app/dist ./dist
COPY --chown=65532:65532 --from=builder /app/package.json ./
# Entrypoint is already node, so CMD is just the script path
CMD ["dist/server.js"]
A single multi-stage Dockerfile that builds and prunes in a full Node stage, then copies only node_modules, dist and package.json into either a non-root Alpine target or a distroless nonroot target, with ownership set to match the runtime user.
When should you avoid Alpine for Node because of musl libc?
Pinning decides when your base changes. The libc decides whether your dependencies run at all.
Alpine uses musl libc, while Debian-based and distroless Node images use glibc. Pure JavaScript doesn't care, but native addons do. A compiled .node file links against one libc and won't load on the other. Packages that ship prebuilt binaries usually publish separate musl and glibc variants. If no musl build exists for your Node version and architecture, the install step falls back to compiling from source. That needs Python, make, and a C++ toolchain in the image. If those are missing, the build fails. If they are present, they end up in a layer you meant to keep lean.
Behavior can also differ when nothing fails outright. People have reported that musl's DNS resolver handles resolv.conf options and large responses differently from glibc, which can surface as intermittent lookup failures inside Kubernetes. musl's memory allocator has also been reported as slower under allocation-heavy workloads. Measure your own service before assuming either way. The common workaround is a glibc compatibility layer on top of Alpine, which mostly cancels the reason you chose Alpine.
Audit before you choose
Check your dependency tree for native code:
- Search
node_modulesfor compiled.nodefiles andbinding.gypfiles. - Look for packages that depend on
node-gyp,node-gyp-build, orprebuild-install.
If you find any, compile them in a build stage that uses the same libc as your runtime stage. Compile on Alpine to run on Alpine, and on Debian to run on distroless. Never copy node_modules across libc families.
#!/usr/bin/env bash
# Audit a project's installed dependencies for native code before picking a base image.
# Run this after `npm ci`, ideally in the same image family as your build stage.
set -euo pipefail
cd "${1:-.}"
echo "== Compiled native addons (.node files) =="
# Any hit here is a binary that is linked against one specific libc.
find node_modules -type f -name '*.node' 2>/dev/null || true
echo
echo "== Packages with binding.gyp (compiled from source when no prebuild matches) =="
# Skip node-gyp's own test fixtures so they don't show up as false positives.
find node_modules -name binding.gyp -not -path '*/node-gyp/*' 2>/dev/null \
| sed 's#/binding.gyp$##' || true
echo
echo "== Dependency paths that pull in native build or prebuild helpers =="
# npm ls exits non-zero when a package is absent, so ignore the exit code.
for helper in node-gyp node-gyp-build prebuild-install; do
echo "-- $helper"
npm ls "$helper" --all 2>/dev/null || echo " (not found)"
done
echo
echo "== libc each addon was linked against =="
# glibc builds need libc.so.6. musl builds need libc.musl-<arch>.so.1.
# readelf comes from binutils and may not be installed in slim images.
if command -v readelf >/dev/null 2>&1; then
find node_modules -type f -name '*.node' 2>/dev/null | while read -r addon; do
libc=$(readelf -d "$addon" 2>/dev/null | grep -o 'libc[^]]*' | head -n1 || true)
echo "${libc:-unknown} $addon"
done
else
echo "readelf not available; install binutils to check linkage"
fi
This script finds compiled addons, source-build markers, and native install helpers in node_modules, then reports which libc each addon is linked against so you can confirm the build stage and runtime stage use the same libc.
How do signals, PID 1, and health checks work without a shell?
Distroless images ship without /bin/sh, so shell-form instructions like CMD node server.js fail at startup: Docker wraps them in /bin/sh -c, which doesn't exist. Use exec form (a JSON array) for both CMD and ENTRYPOINT. The distroless Node images already set node as the entrypoint, so CMD usually only needs the path to your script.
Node as PID 1
Exec form makes Node PID 1, which changes how it handles signals. The kernel does not apply default signal actions to PID 1, so a SIGTERM with no registered handler is ignored. docker stop or a Kubernetes pod deletion then waits out the grace period and sends SIGKILL. In-flight requests are dropped and connections are never closed cleanly.
Register a handler with process.on('SIGTERM', ...). In it, stop accepting new connections with server.close(), drain or close database pools, and exit. Add a timeout so a hung connection can't block shutdown indefinitely.
Node also doesn't reap orphaned child processes. If your service spawns subprocesses, run under an init process. Docker's --init flag injects tini at runtime. Alternatively, copy a statically linked tini binary into the image and make it the entrypoint, so the fix doesn't depend on how the container is launched.
Health checks
A HEALTHCHECK that runs curl or wget fails on distroless because neither tool exists in the image. Use an exec-form check that runs a small Node script, or move health checks to orchestrator HTTP probes. HTTP probes are usually cleaner because they don't spawn a process inside the container.
Migration cost
Exec form doesn't expand environment variables, so ${PORT} in CMD stays literal. Logic from entrypoint shell scripts, such as templating, waiting for dependencies, or running migrations, must move into application code, init containers, or orchestrator config.
// server.js: started via exec form, e.g. CMD ["server.js"] on distroless
const http = require('node:http');
// Exec form does not expand ${PORT}, so read env vars in the app itself.
const port = Number(process.env.PORT) || 8080;
let shuttingDown = false;
const server = http.createServer((req, res) => {
if (req.url === '/healthz') {
// Fail the probe while draining so the orchestrator stops routing traffic here.
res.writeHead(shuttingDown ? 503 : 200).end(shuttingDown ? 'draining' : 'ok');
return;
}
res.end('hello');
});
server.listen(port);
function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal} received, draining connections`);
// Stop accepting new connections. The callback runs once in-flight requests finish.
server.close(async () => {
// await dbPool.end(); // close database pools and other clients here
process.exit(0);
});
server.closeIdleConnections(); // release idle keep-alive sockets immediately
// Hard deadline, kept below the orchestrator's grace period, so a hung socket can't block exit.
setTimeout(() => { console.error('forced exit'); process.exit(1); }, 10_000).unref();
}
// As PID 1, Node ignores SIGTERM unless a handler is registered.
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
A minimal Node HTTP server meant to run as PID 1 in a distroless container: it reads PORT from the environment, exposes a /healthz endpoint for orchestrator HTTP probes, and handles SIGTERM by draining connections with a forced-exit timeout.
How do you debug a distroless Node container in production?
When kubectl exec fails with "executable file not found", responders lose the habit of shelling in to poke around. That habit was always a crutch. A team with structured logs, request-level metrics, and traces rarely needs a shell in a running container. A team without them will feel the gap during an incident.
You have three ways to get visibility back.
Debug variants
Distroless publishes :debug tags that add a BusyBox shell to the same base. They are useful for reproducing a problem locally or in staging against an identical runtime. Don't ship them to production by default, because that brings back the shell you removed on purpose.
Ephemeral debug containers
In Kubernetes, kubectl debug with --target attaches a temporary container, such as BusyBox or a full toolbox image, to a running pod. It shares the target container's process namespace. From there you can see the Node process, read /proc/<pid>/environ, and browse its filesystem through /proc/<pid>/root, all without touching the production image. This requires a cluster version and RBAC policy that allow ephemeral containers, so confirm that before you need it.
Inspecting from outside
docker cp and docker export pull files out of a container without a shell inside it. Heap snapshots and diagnostic reports written by Node to a mounted volume can be analysed on any machine.
Write these procedures into your runbooks and practise them before switching. The time responders spend learning them is a real cost of choosing distroless.
Does a smaller base image make a Node container more secure?
Partly, and less than CVE dashboards suggest. Fewer packages give a scanner fewer components to flag and leave an attacker with fewer tools after compromise. Without a shell or package manager, a typical exploit chain that downloads a payload with curl and runs it through sh has nothing to call. That forces an attacker to do more work inside the Node process itself, which is a real gain.
But the code you ship is still the main attack surface. A prototype-pollution bug in a transitive npm dependency, an unvalidated deserialisation path, or a server-side request forgery in your own handlers is exploitable on any base. Two configuration mistakes outweigh the base choice:
- Running as root. If the process is compromised, root inside the container makes container escapes and writes to mounted volumes much easier. Set a non-root user explicitly, whichever base you use.
- Secrets in layers. An
.npmrctoken copied into an early stage and deleted later can still be recovered if that stage's layers are pushed, cached in a registry, or copied forward by mistake. Use build-time secret mounts instead.
Why CVE counts don't compare across bases
Scanners mostly find OS components by reading package metadata: the apk database on Alpine and dpkg records on Debian and distroless. Each distribution publishes its own advisory data, with different coverage and different triage decisions. Binaries copied in without metadata, such as a Node runtime unpacked from a tarball, may be missed or only found by binary analysis. A lower count can mean the scanner saw less, not that the image contains fewer vulnerabilities.
Which should you choose: distroless, Alpine, or slim Debian?
The choice comes down to how much operational control your team needs over the OS layer, and how much maintenance it will accept.
| Base | Choose it when | Main cost |
|---|---|---|
| Alpine | You need a shell, must install extra OS packages, and have confirmed the dependency tree works on musl | Testing native modules against musl, and occasional DNS or performance differences |
| Distroless | You want a strict security posture, rely on glibc-dependent native modules, and have mature logging, metrics and tracing | Limited control over the OS layer, and debugging that depends on external tooling |
| Slim Debian | You want glibc compatibility with a package manager available | More packages to patch and scan than distroless |
Alpine works well when engineers still exec into containers or when the image needs extra packages at build time. That convenience depends on a one-time musl audit. The audit must be repeated whenever a native dependency changes.
Distroless removes the shell and package manager. This is why it suits teams whose observability already answers production questions from outside the container. The trade-off is that you can't easily add to the OS layer. If you need a custom CA bundle, fonts for PDF rendering, or image libraries for a module like sharp, you have to copy those files in from a builder stage. Every library you copy that way becomes something you track and patch yourself.
Slim Debian variants are the middle ground. They use the same glibc as most prebuilt binaries and keep apt for exceptions. They are also the cheapest starting point for teams migrating from full Debian images.
Migration cost increases from slim, to Alpine, to distroless. Distroless asks you to change your Dockerfile and also how you debug and operate the service.
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
.envby 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.