If you want to reduce Docker image size, most guides hand you the same list: use Alpine, write a multi-stage build, add a .dockerignore, done. All of that is true. What none of those lists tell you is how much each step actually saves, which step barely matters, and which one looks like it helps but saves nothing at all. That is what we wanted to know. The trigger was our own Coolify review: its default build pack turned a tiny Node app into a 1.04 GB image, and we wrote that a hand-written Dockerfile would be “much smaller”. Today we measured it.
On 26 November 2026 we took the same small Express app and built it with eight different Dockerfiles on our development server running Docker 29.9.3 (BuildKit, containerd snapshotter). We started each result, measured it, and scanned it for known vulnerabilities with Trivy 0.76.1. We also took a Go program from 1.37 GB down to under 8 MB. Afterwards we deleted every test image and base image again. The four key findings up front:
1. The naive Dockerfile (
FROM node:22,COPY . .,npm install) produced 1.83 GB. The best Node variant on Alpine came in at 248 MB, distroless at 210 MB. That is 86 to 89 % smaller, and almost all of the saving came from one single step: the base image.2.
RUN rm -rfon a later line saves nothing. Our “cleanup layer” was 12.3 kB, and the image stayed at 443 MB, even though the deleted files were around 100 MB.3. Smaller means safer, but not linearly: the naive image had 3,920 known vulnerabilities (20 critical), Alpine in a multi-stage build 34, and after removing npm from the final image just 11, none of them high or critical.
4. Image size makes no difference to memory. Every variant used between 13.7 and 17.7 MiB of RAM at idle.

Why reduce Docker image size at all?
Before the techniques, an honest question: is it worth it? Disk space is cheap, and a 1.8 GB image runs just as well as a 250 MB one. Still, there are four solid reasons:
- Disk space on the server. An image rarely comes alone. Every build leaves old versions and build cache behind. After this test our development server had 5.5 GB of build cache lying around and the disk was at 97 %. How quickly that tips over is something we covered in Linux disk full.
- Transfer time. Every deploy, every new server and every CI run pulls the image. What travels is the compressed size, and for us that ranged from 488 MB (naive) to 53 MB (distroless).
- Attack surface. Every package in the image is code that can have bugs. A shell, a package manager, compilers, image libraries: your app needs none of them at runtime, but all of them show up in a security scan.
- Build time. A lean Dockerfile almost always has a clean layer order too, and that makes rebuilds faster. In our test: 4.2 seconds versus 0.4 seconds for the same code change.
What does not get faster is container start-up and memory use. A container is a normal Linux process (more on that in What is Docker?). Unused files in the image only sit on disk; they are not loaded into RAM.
Our test setup
To keep the numbers comparable, we built every variant from exactly the same project folder:
- App: an Express server with a single route that returns
okplus the Node version. - Dependencies:
expressas the runtime dependency, plustypescript,eslint,@types/nodeand@types/expressas dev dependencies, just like almost every real project. Together that is 141 packages and 46 MB innode_modules. The runtime dependencies alone are 4.8 MB. - Ballast: a 60 MB
.gitfolder standing in for a grown Git history. Every real repository has one, and without a.dockerignoreit ends up in the image viaCOPY . .. - Environment: Docker 29.9.3, BuildKit (buildx 0.38.1),
overlayfsstorage via the containerd snapshotter, Ubuntu 24.04.
For each variant we measured the size on disk (docker image inspect), the compressed size (docker save | wc -c, roughly what a pull transfers), build time, idle RAM and Trivy’s vulnerability count.
Two sizes that are easy to mix up
Since Docker started using the containerd snapshotter, docker images shows two columns: Disk Usage and Content Size. Our naive image showed 1.83 GB and 488 MB. Both are correct. The first is unpacked on disk, the second is compressed, the way it sits in a registry. If you read two articles quoting different sizes for the same base image, this is often the reason. Throughout this article we give the on-disk size first and the compressed size in brackets.
Results at a glance
| Variant | Base | Size (disk) | Compressed | Vulnerabilities (Trivy) |
|---|---|---|---|---|
| 1 naive | node:22 | 1.83 GB | 488 MB | 3,920 (20 critical) |
1b naive + .dockerignore | node:22 | 1.70 GB | – | – |
| 2 base image swapped only | node:22-slim | 531 MB | 160 MB | 273 (1 critical) |
6 “cleanup” via rm | node:22-alpine | 443 MB | 141 MB | – |
| 3 Alpine, prod deps only | node:22-alpine | 251 MB | 63 MB | – |
4 as 3 + clean cache + USER node | node:22-alpine | 248 MB | 62 MB | – |
| 7 multi-stage Alpine | node:22-alpine | 245 MB | – | 34 (0 critical) |
| 8 multi-stage Alpine without npm | node:22-alpine | 245 MB | – | 11 (0 high) |
| 5 multi-stage distroless | distroless/nodejs22 | 210 MB | 53 MB | 100 (1 critical) |
For comparison, the bare base images as pulled from Docker Hub and gcr.io on 26 November 2026: node:22 1.62 GB (425 MB compressed), node:22-slim 326 MB (82.5 MB), node:22-alpine 239 MB (61.8 MB), gcr.io/distroless/nodejs22-debian12 204 MB (52.6 MB). If you look closely, the real result of this article is already visible here: our app itself is only about 5 to 10 MB in every case. Everything else is the foundation you put it on.
Below we go through the steps in the order you should tackle them in a real project: biggest lever first.
Step 1: Pick the right base image
Our naive Dockerfile looked the way most Dockerfiles look at the beginning:
FROM node:22
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "server.js"]
Result: 1.83 GB. Then we changed only the first line, to FROM node:22-slim. Nothing else. Result: 531 MB, a 71 % reduction from one change. No other step in this article comes anywhere close.
The reason is easy to find. The default node:22 image is built on the full Debian buildpack-deps image, which is meant for compiling native extensions. We counted: 413 installed Debian packages and 666 programs in /usr/bin, including compilers, Git, Python, ImageMagick libraries and database headers. node:22-slim has 88 packages, node:22-alpine just 19 Alpine packages.

Which base for what?
node:22(full, Debian): only as a build stage when you have to compile native modules (for examplebcrypt,sharpwith custom libraries,node-gyp). Almost never sensible as a final image.node:22-slim(Debian, trimmed): the safe middle ground. Same C library (glibc) as most servers, so few compatibility surprises. A shell andaptare still there, which helps when debugging.node:22-alpine: even smaller, but uses musl instead of glibc. For pure JavaScript apps like ours that does not matter. With prebuilt native modules it can break, because those are built for glibc. npm then compiles them during install, and Alpine is missing the compilers for that.- Distroless: no package manager, no shell, just the runtime and its libraries. More on that in step 6.
One detail surprised us: the gap between slim and Alpine, 326 versus 239 MB, was smaller than many articles suggest. The bulk of a Node image is Node itself (the binary alone is over 100 MB) plus the bundled npm. That stays the same whichever base you choose.
Step 2: Add a .dockerignore
Our project folder contained the 60 MB .git folder and locally installed node_modules. Without a .dockerignore, Docker sends everything to the daemon during the build. The build log says so in plain text:
#6 transferring context: 62.93MB 0.2s done
With this three-line .dockerignore next to it:
node_modules
.git
Dockerfile*
that became:
#5 transferring context: 204B 0.0s done
From 62.93 MB to 204 bytes. The naive image shrank from 1.83 to 1.70 GB. That sounds small because the base image is so huge. In a lean image, those 60 MB would have been a quarter of the total. Often something else matters more than size here: what is not in the build context cannot accidentally end up in the image. That includes .env files with passwords, local databases, SSH keys and the full Git history, from which deleted secrets can be recovered. A docker exec into our naive image really did show the .git folder at 61 MB under /app/.git.
Our recommended starting point for Node projects:
node_modules
npm-debug.log
.git
.gitignore
.env
.env.*
Dockerfile*
docker-compose*.yml
coverage
.vscode
.idea
*.md
Step 3: Install production dependencies only
npm install also installs dev dependencies: TypeScript, ESLint, type definitions. In our test they accounted for over 40 of the 46 MB in node_modules. The server needs none of them at runtime.
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server.js ./
CMD ["node", "server.js"]
Result: 251 MB, with only 10 MB in the install layer. Two things matter here:
npm ciinstead ofnpm install.ciinstalls exactly what is inpackage-lock.jsonand fails if the lockfile andpackage.jsondo not match. That makes builds reproducible.npm cidoes not work without a lockfile, sopackage-lock.jsonbelongs in the repository.- Copy selectively instead of
COPY . .. We only copy what the app needs. In bigger projects that is a folder such asdist/orsrc/. Tests, docs and config files stay out of the image.
If your app has a build step, such as compiling TypeScript or building a frontend, you do need the dev dependencies while building. Then there is no way around a multi-stage build (step 5).
Cleaning the cache: a small win
With npm ci --omit=dev && npm cache clean --force on the same RUN line, the layer shrank from 10 MB to 7.8 MB and the image from 251 to 248 MB. That is the smallest lever in this article. In projects with hundreds of dependencies the npm cache gets bigger and the step pays off more. With apt, the rule is the same and matters more, because package lists easily reach 20 to 40 MB:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
--no-install-recommends stops apt from pulling in “recommended” extra packages. That often saves more than the cleanup itself.
The trap: cleaning up on a separate RUN line
This is the most common mistake when people try to reduce Docker image size. We reproduced it on purpose:
FROM node:22-alpine
WORKDIR /app
COPY . .
RUN npm install
RUN rm -rf node_modules/typescript node_modules/eslint .git
CMD ["node", "server.js"]
The idea sounds reasonable: install first, then throw the ballast away. The result: 443 MB. And docker history shows why:
12.3kB RUN /bin/sh -c rm -rf node_modules/typescript ...
61.5MB RUN /bin/sh -c npm install
63MB COPY . .
A Docker image is a stack of layers, and every layer is immutable. The rm line does not remove the files from the layers below; it only adds a new 12.3 kB layer on top that says “please hide these files”. In the running container they are gone. In the image, on disk and on every pull they are still there. Unpack a docker save and you will find them intact, .git folder included.
The rule: anything you do not want in the image must either never get in (.dockerignore, selective COPY), be deleted on the same RUN line that created it, or stay behind in a build stage that never makes it into the final image. Which brings us to the most effective tool.
Step 4: Layer order for fast builds
Before multi-stage builds, one point that does not affect size but has a huge effect on build time. In two variants we changed a single line in server.js and rebuilt:
- Variant 2 (
COPY . .beforenpm install): Docker sees a changed file in the copied folder, discards the cache and reinstalls all 141 packages. 4.2 seconds. - Variant 4 (copy
package*.jsonfirst, thennpm ci, then the code): the package files are unchanged, so Docker takes the install from cache. 0.39 seconds.
That is more than ten times faster, for a tiny app. In real projects with large dependencies, native modules or frontend builds, 4 seconds quickly becomes a minute per commit. The basic rule: what changes rarely goes at the top. What changes often goes at the bottom.
Step 5: Multi-stage builds
A multi-stage build has several FROM lines. Each one starts a new stage with its own filesystem. Only the last stage ends up in the final image, and with COPY --from= you pick exactly the files you need from earlier stages. Everything else, compilers, dev dependencies, source code, caches, stays behind.

This is our multi-stage variant on Alpine:
# Stage 1: build (with all dependencies)
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY server.js ./
# this is where e.g. "RUN npm run build" would go
RUN npm prune --omit=dev
# Stage 2: ship
FROM node:22-alpine
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/server.js ./
USER node
CMD ["node", "server.js"]
Result: 245 MB, even though all 141 packages including TypeScript and ESLint were installed in the build stage. For our app without a build step that is barely smaller than variant 4. The advantage shows as soon as you compile something: the build stage can be as fat as it likes, and the final image never notices.
How dramatic it can get: Go and scratch
With compiled languages the effect is much bigger, because in the end only a single file is left. We built a minimal Go program (an HTTP server, six lines) twice. Naive:
FROM golang:1.25
WORKDIR /src
COPY . .
RUN go build -o app .
CMD ["./app"]
1.37 GB. And with a multi-stage build on scratch, the completely empty image:
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o app .
FROM scratch
COPY --from=build /src/app /app
USER 65532
ENTRYPOINT ["/app"]
7.98 MB. That is 99.4 % smaller. The server ran and answered with ok go.
We also measured a classic trap along the way. We built the same program with CGO_ENABLED=1 in the full golang image and copied it into scratch. At 12.7 MB the image was even a little larger, but the container would not start. It exited immediately with code 255 and this message:
exec /app: no such file or directory
The file obviously exists. What is missing is the dynamic linker (/lib64/ld-linux-x86-64.so.2) that a dynamically linked binary needs in order to start. In scratch there is nothing, not even a linker. The error message is notoriously misleading. If you see it, check CGO_ENABLED=0 first or switch to gcr.io/distroless/static instead of scratch. One more note on scratch: it has no CA certificates and no time zone data either. If your program makes HTTPS calls, copy /etc/ssl/certs/ca-certificates.crt over from the build stage.
Step 6: Distroless, if you want even less
Google’s distroless images contain only the runtime (here Node.js 22) and the libraries it needs. No shell, no package manager, no ls. Our multi-stage build for it:
FROM node:22-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server.js ./
FROM gcr.io/distroless/nodejs22-debian12
WORKDIR /app
COPY --from=build /app /app
USER nonroot
CMD ["server.js"]
Note the last line: in the distroless image node is already the entrypoint, so CMD only names the script. Result: 210 MB (53 MB compressed), the smallest Node image in our test.
Two things you should know that distroless marketing rarely mentions:
- No shell means no debugging via
docker exec. Our attempt to get in withdocker exec ... shended withexec: "sh": executable file not found in $PATH. For debugging there are:debugvariants with a BusyBox shell, which you should not run in production. - You get whatever Node version Google last built. Our distroless image shipped Node v22.22.0, while the official
node:22images on the same day had v22.23.5. It also had an older Debian base (12.13 instead of 12.15 innode:22-slim). That sounds minor, but it directly affects the security scan.
Video by LearnITGuide Tutorials (September 2026) that explains the layer mechanics behind multi-stage builds clearly.
Smaller equals safer? The security scan
We scanned four variants with Trivy 0.76.1 and the vulnerability database from 26 November 2026. The counts include every reported known vulnerability (CVE) in OS packages and Node packages:
| Variant | Total | Critical | High |
|---|---|---|---|
naive (node:22) | 3,920 | 20 | 479 |
node:22-slim | 273 | 1 | 48 |
| distroless | 100 | 1 | 6 |
| multi-stage Alpine | 34 | 0 | 10 |
| multi-stage Alpine without npm | 11 | 0 | 0 |

Three observations that matter more to us than the raw numbers:
1. The base image decides almost everything. We went from 3,920 to 273 findings just by switching from node:22 to node:22-slim, the same one-line change as for size. Most findings in the full image concern libraries our app never calls. For an attacker who is already inside the container, they are still tools.
2. Distroless is not automatically the safest. All 7 high and critical findings in the distroless image were in a single package: libssl3, including the critical CVE-2026-31789. The cause is the image’s older Debian base. Distroless cuts the number of packages, but you depend on how quickly the image gets rebuilt. A node:22-slim that you pull fresh every week can be more current than a distroless image.
3. Most of what was left in Alpine was npm itself. All 10 high findings in the Alpine variant sat in /usr/local/lib/node_modules/npm, the package manager bundled with the official Node image (brace-expansion, picomatch, ip-address, sigstore, pacote). Your app does not need npm at runtime, so we removed it in the shipping stage:
FROM node:22-alpine
RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/corepack \
/usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \
/opt/yarn* /usr/local/bin/yarn*
WORKDIR /app
COPY --from=build /app ./
USER node
CMD ["node", "server.js"]
Result: 11 findings, none of them high or critical. The size stayed at 245 MB, though, for exactly the reason from our rm trap: npm lives in a layer of the base image, and deleting it only hides it. For the scanner and for an attacker it is gone; on disk it is not. This is the one case where a later rm line still makes sense. If you used npm start as your start command, switch to node server.js, which is better anyway because signals like SIGTERM then reach Node directly.
Run as non-root
Independent of size: the naive image ran as root (UID 0). In variants 4, 7 and 8 we set USER node, in distroless USER nonroot. The official Node images already include the node user with UID 1000; you just have to switch to it. It costs zero bytes and one line. If you want to restrict privileges further, our Docker vs Podman comparison covers rootless containers.
RAM and start-up: what does not change
We started the variants and measured memory after three seconds of idling with docker stats:
- naive (
node:22, 1.83 GB): 17.1 MiB - Alpine (248 MB): 17.7 MiB
- distroless (210 MB): 15.8 MiB
- multi-stage Alpine (245 MB): 13.7 MiB
The differences are noise. A 1.8 GB image does not need more RAM than a 210 MB image, because the kernel only loads the files the process actually opens. If you are trying to reduce Docker image size to save memory, you are optimising the wrong thing. That is down to the runtime you choose and how the app is configured.
Tools: where is the size hiding?
Before you optimise someone else’s or a grown Dockerfile, find out which layer is how big. The built-in command is almost always enough:
docker history --format '{{.Size}}\t{{.CreatedBy}}' my-image:latest
The output lists every layer with its size and the line that created it. That is how we spotted the 12.3 kB rm layer sitting on top of the 61.5 MB install. Other useful commands:
docker images # Disk Usage and Content Size
docker image inspect -f '{{.Size}}' my-image # size in bytes
docker system df # images, containers, volumes, build cache in total
docker run --rm my-image du -sh /app/node_modules # what lives where?
For an interactive view there is the open-source tool dive, which shows layer by layer which files were added, changed or overwritten. We did not use it in this test because docker history answered every question.

What about Nixpacks and buildpacks?
Platforms like Coolify, Railway or Heroku often build images automatically, without you writing a Dockerfile. In our Coolify review, Nixpacks produced 1.04 GB for a small Fastify app. That is a different app from the one in this test, so the numbers are not directly comparable. The order of magnitude is clear, though: an automatically generated image sits in the same class as our naive Dockerfile, and a hand-written Alpine Dockerfile at roughly a quarter of that.
That does not make buildpacks bad. They save you the Dockerfile, detect languages on their own and work reliably. You pay in disk space and transfer time. For a prototype that is often a good trade. For an app you deploy several times a day, your own Dockerfile pays off, and most platforms let you choose between a buildpack and a Dockerfile.
Beginner tutorial by CodeLucky (August 2025, so slightly older; the fundamentals have not changed since).
The checklist: reduce Docker image size in the right order
Ranked by impact, as measured in our test:
- Switch the base image (
node:22→-slimor-alpine). For us −71 % to −86 %. Biggest lever, one line. - Multi-stage build as soon as there is a build step or you compile anything. For Go −99.4 %.
- Production dependencies only (
npm ci --omit=dev,pip install --no-cache-dir,apt-get install --no-install-recommends). - Add a
.dockerignore. Saved 130 MB for us and keeps secrets out of the image. - Copy selectively instead of
COPY . .. - Clean up on the same
RUNline, never on a separate one. - Layer order: package files first, code last. Made rebuilds ten times faster for us.
- Remove runtime ballast (npm, corepack, yarn) if you want a clean security scan.
- Set
USERso the container does not run as root. - Rebuild regularly so the base image stays current. A small, stale image is not safer than a larger, fresh one.
And clean up: every build leaves cache behind. docker builder prune and docker image prune belong on every server that builds images. How to do that without deleting anything important is in Linux disk full. If you run several containers together, our Docker Compose example shows how to wire up the lean images afterwards.
Limits of these measurements
To be honest about what this test does not show:
- One single, very small app. In projects with many dependencies or native modules the proportions shift.
node_modulesbecomes the largest item, and multi-stage plus--omit=devgains relatively more. - Python, PHP and Java were not measured. The principles are the same; the numbers are not.
- Vulnerability counts are a snapshot. They depend on the database version and the day of the pull. Tomorrow there could be more or fewer. Many findings concern code your app never executes; they measure attack surface, not acute danger.
- Build times for the first build include downloading the base image and are therefore only roughly comparable. The rebuild comparison (4.2 versus 0.4 seconds) is the meaningful one, because everything was local.
After the test we deleted all test images, the four Node base images and the test folder. The list of images on the server was identical to the one before the test.
Conclusion
Reducing Docker image size is less of an art than the many guides suggest. In our test more than 70 % of the saving came from a single line, the base image. Multi-stage builds are the tool for anything that gets compiled or built, and they turn a 1.37 GB Go image into 8 MB. The remaining tricks save a few megabytes each, with one exception: RUN rm -rf on its own line saves nothing at all.
Our recommendation for most Node projects: multi-stage with node:22-alpine (or -slim if native modules cause trouble), npm ci --omit=dev, a .dockerignore, USER node and npm removed from the final image. That gets you to roughly a seventh of the naive size and a fraction of the security findings, while keeping a shell for debugging. Distroless is a good choice if you keep your base image strictly up to date. Otherwise a freshly pulled Alpine or slim image is the more robust option.
Frequently asked questions
How can I reduce Docker image size?
The most effective measure is a smaller base image, such as node:22-alpine or node:22-slim instead of node:22. After that come multi-stage builds, a .dockerignore file, production-only dependencies and cleaning caches on the same RUN line. In our test a Node app went from 1.83 GB to 248 MB this way.
What is a multi-stage build?
A Dockerfile with several FROM lines. Each line starts its own stage. Only the last stage ends up in the final image; from earlier stages you pick files with COPY --from=<stage>. Compilers, dev dependencies and source code stay behind in the build stage.
Why does my image not get smaller when I delete files?
Because every line in a Dockerfile creates an immutable layer. A RUN rm on a later line only hides files; they stay stored in the layer underneath. In our test the delete layer was 12.3 kB and the image stayed at 443 MB. Delete on the same RUN line or use a multi-stage build.
Is Alpine better than Debian slim?
For pure JavaScript, Go or Python apps without native extensions, usually yes, because Alpine is smaller and ships fewer packages. But Alpine uses musl instead of glibc. Prebuilt native modules and some Python wheels do not work there or have to be recompiled. In that case -slim is the less stressful choice. In our test the two were only 87 MB apart.
What is distroless?
Images maintained by Google that contain only a runtime and its libraries, without a shell or package manager. Our Node image on distroless was the smallest at 210 MB. Downsides: no docker exec with a shell, and the bundled Node version in our test was older than in the official Node image.
What does a .dockerignore file do?
It defines which files are never handed to Docker during the build. Our build context dropped from 62.93 MB to 204 bytes. Even more important: files like .env, .git or local databases cannot end up in the image by accident.
Does a smaller image make my container faster?
Barely, at start-up or at runtime. All our variants used between 13.7 and 17.7 MiB of RAM at idle, whether the image was 210 MB or 1.83 GB. What gets faster are pulls, deploys and CI runs, because less data is transferred.
How do I find out what makes my image so big?
With docker history <image>. It shows every layer with its size and the Dockerfile line that created it. With docker run --rm <image> du -sh /path you can look into individual folders. The dive tool offers the same as an interactive view.
Why does docker images show two different sizes?
Newer Docker versions using the containerd snapshotter show “Disk Usage” (unpacked on disk) and “Content Size” (compressed, as in the registry). Our naive image was 1.83 GB on disk and 488 MB compressed. A pull transfers roughly the compressed size.
Is a smaller image automatically more secure?
Usually, but not necessarily. Fewer packages mean fewer possible vulnerabilities: our naive image had 3,920 findings, the Alpine variant without npm only 11. How current the base image is matters too. The smaller distroless image had a critical finding from an outdated OpenSSL version that the Alpine image did not have.
What is the scratch image?
A completely empty image with no files. It suits statically linked programs, typically Go with CGO_ENABLED=0. Our Go server came to 7.98 MB in it. A dynamically linked binary will not start in scratch and reports the misleading exec /app: no such file or directory.
How often should I rebuild my image?
Regularly, even without code changes, so security updates from the base image get in. Weekly via CI is a good rhythm. Build with --pull so Docker does not reuse the old base image cached locally.