
2025-09-04
10 min read
How to reduce Docker image size (Especially NodeJs) by almost 92% !! from 2.03 GB to 163 MB
The problem and risks (Terminology)
Imagine you have a computer that has only 10GB of total storage and you have 5 installed games each takes 2GB, the main problem the full capacity is taken and this is hugely affecting the performance of other games, now you know one of the games can be somehow compressed or size be reduced by deleting some of it is unnecessary files and packages.
The real problem that I encountered
I was working on CI/CD at my workspace using AzureDevOps and a private container registry. We encountered an issue with our front-end application: once containerized, the image size ballooned to nearly 2 GB! my co-worker notified me about this and said that it is really possible to reduce the image size to more than 50%.
This caused two main problems:
- It consumed a large amount of space on the VM hosting our private Docker registry, and on the machine that will pull the image to deploy the app.
- It significantly increased build times in our CI process.
How to actually reduce the docker image size for a NodeJs app ?
Don't forget a .dockerignore file in your workspace !!!
You really don't want unnecessary files or directories in your image (like .node_modules, unnecessary config files, etc.) so best idea to create a .dockerignore file at the the root of project on same level of Dockerfile.
that will have something like:

Use a multi-stage build strategy in your Dockerfile
This involves defining multiple stages in your Dockerfile.
The first stage handles building the application and installing dependencies.
In the final stage, only the necessary files are copied, excluding development dependencies and build-time files. This reduces the image size and ensures that only essential components are included in the production image, improving efficiency and security.

Reduce the number of layers in your Dockerfile !
If you can combine commands or bash scripts into one line, do it! This helps minimize the number of layers in the image.

Choose Lightweight Base Images for Maximum Impact
The base image you select has the biggest impact on your final image size. Standard Node.js images can be bloated with unnecessary system packages and tools. Instead, opt for minimal variants:
- Alpine images (node:18-alpine): Based on Alpine Linux, typically 5-10x smaller than standard images
- Slim images (node:18-slim): Debian-based but with non-essential packages removed
- Distroless images (from Google): Contains only your app and runtime dependencies, no shell or package managers
Example size comparison:
- node:18 → ~900MB
- node:18-slim → ~240MB
- node:18-alpine → ~110MB
Is it is worth nothing but to mention that these articles that helped me achieve that: