Cut a Node.js Docker image from about 1.2GB to under 200MB with multi-stage builds, a slim base, and .dockerignore. Includes caching tips.
A backend team ships a Node.js service whose Docker image is 1.2GB. Registry storage keeps climbing, and every new Kubernetes node needs a long pull before a pod can start. During traffic spikes, that pull time shows up as slow scale-out. This scenario is a composite, but the numbers are typical.
Three changes later the image is under 200MB. Same application, same code, and pulls take a fraction of the time. This guide shows what changed and why, how much reduction to expect for other languages, and how to keep the result from regressing.
Docker images get large because of the base image and the build tooling, almost never because of your application code. A default node base image bundles the full runtime, npm, yarn, a package manager, curl, git, a C toolchain, Python, and hundreds of system libraries. Your own code is typically 5 to 50MB.
| Layer | Typical size | Needed at runtime? |
|---|---|---|
| Full Debian base image | ~950MB | Mostly no |
| Build tools and dev deps | ~180MB | No |
| Node.js runtime | ~120MB | Yes |
| Application code | ~10MB | Yes |
Treat these as illustrative figures for a mid-sized TypeScript service. Run docker history <image> on your own image to see the real split. The fix is not smaller application code. It is a minimal runtime image that contains only what the running process needs.
Reduction depends on whether your runtime stage can shed the interpreter. Compiled languages with static binaries shrink the most, while interpreted languages keep their runtime.
| Language | Typical reduction |
|---|---|
| Go (static binary) | 90-99% |
| Rust (musl static) | 90-99% |
| Java (JRE-slim) | 70-85% |
| Node.js | 70-90% |
| Python | 50-70% |
These are ranges you can expect from multi-stage builds with a slim or distroless runtime, not guarantees. Always measure with docker images before and after.
A multi-stage build uses one stage to compile and another to run. The build stage holds compilers and dev dependencies, the runtime stage starts fresh, and you copy only the built output across. Everything else is discarded with the builder stage.
## WRONG: single stage, everything stays in the imageFROM node:24WORKDIR /appCOPY package*.json ./RUN npm ciCOPY . .RUN npm run buildCMD ["node", "dist/index.js"]## Result: well over 1GBThe corrected version uses three stages: one to build, one to install production dependencies only, and a small runtime stage.
## Stage 1: build with all dependenciesFROM node:24-alpine AS builderWORKDIR /appCOPY package*.json ./RUN --mount=type=cache,target=/root/.npm npm ciCOPY . .RUN npm run build ## Stage 2: production dependencies onlyFROM node:24-alpine AS prod-depsWORKDIR /appCOPY package*.json ./RUN --mount=type=cache,target=/root/.npm \ npm ci --omit=dev ## Stage 3: minimal runtimeFROM node:24-alpine AS runtimeENV NODE_ENV=productionWORKDIR /appCOPY --from=prod-deps --chown=node:node \ /app/node_modules ./node_modulesCOPY --from=builder --chown=node:node \ /app/dist ./distCOPY --chown=node:node package.json ./USER nodeEXPOSE 4000CMD ["node", "dist/index.js"]Parameter breakdown:
AS builder: names the stage so later stages can reference it.COPY --from=builder: copies files from a named stage and not from your filesystem.--omit=dev: tells npm to skip devDependencies in the production stage.npm ci: installs exactly what the lockfile says, which is faster and reproducible.--mount=type=cache: keeps the npm download cache between builds without storing it in any image layer.The compiled output, the TypeScript compiler, the test framework, and every devDependency never reach the final image.
š Remember: Node 18 reached end of life in 2025, so the examples above use a current LTS line. Pick the newest Node LTS your dependencies support, and pin it to a specific minor version in production.
Start with the smallest base that your dependencies tolerate. Alpine uses musl libc and busybox, so its base is a small fraction of a Debian base. A -slim Debian variant sits in between, and distroless removes the shell and package manager entirely.
| Base | Size | Trade-off |
|---|---|---|
| Debian (full) | Largest | Everything included, most CVEs |
| Debian slim | Medium | glibc compatible, stripped |
| Alpine | Small | musl libc can break native modules |
| Distroless | Small | No shell, harder to debug |
Alpine breaks packages that ship prebuilt glibc binaries. The usual victims are image-processing libraries such as sharp or canvas, some database drivers, and crypto modules with native code. The failure shows up as a missing loader or relocation error at startup, not as an arch mismatch.
## Test Alpine compatibility before committingdocker build -t payment-api:alpine-test .docker run --rm payment-api:alpine-test \ node -e "require('./dist/index')"If this fails, build the native dependency inside the Alpine build stage or fall back to node:24-slim for that service. A pure TypeScript API talking to PostgreSQL usually runs fine on Alpine.
Distroless images contain your runtime and CA certificates but no shell or package manager. That removes whole classes of attack and satisfies "no shell in production" controls in SOC 2 style audits. The cost is debugging: you cannot exec into the container, so use kubectl debug with an ephemeral container instead.
A .dockerignore keeps junk out of the build context. Without it, COPY . . sends node_modules, .git, test fixtures, logs, and local .env files to the Docker daemon, and they can end up in the image.
node_modules/dist/.git/.gitignore*.md*.log.env.env.*coverage/__tests__/test/.DS_Storedocker-compose*.ymlMakefileThe bigger payoff is cache stability. If the context contains files that change on every build, such as logs or coverage reports, Docker invalidates the COPY . . layer every time, even when your source has not changed. A proper .dockerignore makes only meaningful changes invalidate the cache. It also keeps secrets like .env out of the image.
Yes. Running as a non-root user and setting NODE_ENV=production are security and runtime improvements, and with the multi-stage layout above they cost nothing in size. The node user already exists in the official images, so USER node is enough.
FROM node:24-alpine AS runtimeENV NODE_ENV=productionWORKDIR /appCOPY --from=prod-deps --chown=node:node \ /app/node_modules ./node_modulesCOPY --from=builder --chown=node:node \ /app/dist ./distUSER nodeEXPOSE 4000HEALTHCHECK --interval=30s --timeout=5s --retries=3 \ CMD wget -qO- http://localhost:4000/health/live || exit 1CMD ["node", "dist/index.js"]Note that Kubernetes ignores the Dockerfile HEALTHCHECK. In Kubernetes, define liveness and readiness probes in the pod spec. Keep HEALTHCHECK for plain Docker and Compose deployments.
Because the cache mount in the earlier stages keeps npm's cache out of the image, you no longer need npm cache clean --force. If you use an older build without BuildKit cache mounts, add it to the same RUN line so the cache is not baked into a layer.
Measure after each change so you know what actually helped:
## Compare image sizesdocker images | grep payment-api ## See where the bytes aredocker history payment-api:finalAn illustrative result for a typical TypeScript API:
| Change | Image size | Why |
|---|---|---|
| Single stage, full base | ~1.2GB | Everything included |
| Multi-stage build | ~380MB | Dev deps and tools removed |
| Alpine runtime | ~180MB | Smaller OS and runtime |
| Cache mount, no npm cache | ~175MB | No leftover cache |
The .dockerignore file barely changes final size, but it protects your cache and your secrets. For a visual breakdown of layers, the open-source dive tool shows exactly which layer holds which files.
Order your Dockerfile from least to most frequently changing. Docker reuses a cached layer only if everything above it is unchanged, so dependency files go first and source code goes last.
FROM node:24-alpine AS builderWORKDIR /app ## Changes only when dependencies changeCOPY package*.json ./RUN npm ci ## Changes on every commitCOPY . .RUN npm run buildIf you reverse the order, every commit re-downloads all packages. A 3-minute build can become a 12-minute build. In GitHub Actions, persist layers between runs with the Buildx cache:
steps: - uses: docker/setup-buildx-action@v3 - uses: docker/build-push-action@v6 with: context: . push: true tags: ${{ env.ECR_REPO }}:${{ github.sha }} cache-from: type=gha cache-to: type=gha,mode=maxWith caching configured correctly, rebuilds that change only application code often finish in well under two minutes instead of several. Check the current major versions of these actions when you copy the snippet.
Smaller is not automatically better. Match the base image to how you debug and how many native dependencies you have.
| Approach | Best for | Watch out |
|---|---|---|
| Alpine runtime | Most Node APIs | musl native module issues |
| Debian slim | Native-heavy services | Larger than Alpine |
| Distroless | Security-sensitive services | No shell for debugging |
| Scratch | Static Go or Rust binaries | No CA certs or shell |
Multi-stage builds work for any language, so use the same pattern for Python (build wheels in one stage, copy them to a slim runtime) and Java (build with a JDK, run on a JRE).
Scan every image before it ships, and rescan on a schedule because new CVEs appear after you build. Smaller images usually have fewer findings because they contain fewer packages, but that is not guaranteed, so verify.
## Fail the pipeline on serious vulnerabilitiestrivy image \ --exit-code 1 \ --severity HIGH,CRITICAL \ payment-api:latest ## Or use Docker Scoutdocker scout cves payment-api:latestThe older docker scan command is deprecated, so use Trivy or Docker Scout instead.
Pin base images to a specific version, and ideally to a digest, so a rebuild does not silently change your runtime. Rebuild on a schedule to pick up patched base layers.
Registry cost matters too. Registries bill for stored gigabytes, so a repository that keeps 20 tags of a 1.2GB image holds 24GB, while the same history at 180MB holds under 4GB. Add a lifecycle policy to expire old tags. Smaller images also reduce pull time on cold nodes, which helps autoscaling during traffic spikes, and in ap-south-1 you should confirm that image pulls use a VPC endpoint for ECR so they do not pay NAT Gateway processing fees.
Finally, add an image size check to CI. Fail the build when an image grows past an agreed budget, so a stray dependency never silently adds hundreds of megabytes.
NoteReferences and Further Reading
- Docker Multi-Stage Build Documentation - Official reference for multi-stage syntax
- Docker Hub: node - Official Node.js image variants and their trade-offs
- Trivy - Container vulnerability scanning before deployment
- dive - Explore image layers and wasted space
No. Scratch has no shell, no package manager, and no CA certificates, so an app that makes outbound HTTPS calls needs the CA bundle copied from the builder stage, and you cannot exec into the container to debug. Distroless or Alpine is the better default for most services. Reserve scratch for static binaries such as Go or Rust.
Alpine uses musl libc instead of glibc. Native modules that ship prebuilt glibc binaries often fail with errors like "ld-linux-x86-64.so.2: No such file or directory" or a symbol relocation error. Rebuild the native dependency inside the Alpine build stage, or switch that service to a -slim Debian-based image.
Usually, but not linearly. Nodes cache layers, so a node that already has your base layers only pulls the changed application layer. Using the same base image tag across services means more shared layers per node, which can matter more than the raw size number.
Docker caches layers in order. If COPY . . runs before the dependency install, every code change invalidates the install layer and re-downloads all packages. Copy package.json and the lockfile first, install dependencies, and only then copy the source so the install layer stays cached across code-only commits.
Yes. Compiled languages with static binaries, such as Go and Rust, can shrink by well over 90% because the runtime stage needs almost nothing. Node.js and Python still need an interpreter and standard library, so typical reductions are smaller, often in the 50 to 85% range depending on the base image you start from.
Discussion0