Kawser
devsafix@gmail.com
Many developers unknowingly create oversized Docker images because they treat Docker like a simple file copier instead of a controlled build environment. The biggest culprit? Including unnecessary files — especially the entire node_modules directory — directly in the production image. This single mistake can inflate your image size dramatically and slow down builds, pulls, and deployments across environments.
When you're working locally, node_modules can easily grow to hundreds of megabytes—sometimes even gigabytes. But shipping all of that into your Docker image is both wasteful and harmful for performance. Production environments do not need development tools, TypeScript compilers, local caches, or unused packages.
Docker’s multi-stage build system allows you to separate the build-time dependencies from the runtime environment. This lets you install devDependencies only in the build phase, generate your output (e.g., a TypeScript dist folder), and then ship only the files that actually matter.
Instead of bundling development tools, compilers, linting packages, and TS configs into the final image, your production container contains only the compiled JavaScript and required production dependencies. This leads to smaller, faster, and more secure images.
With a well-structured Dockerfile, we introduce two separate stages:
devDependencies—runs tests, compiles TypeScript into JavaScript, and prepares everything needed for production. dist folderdist directorypackage.json with only production dependenciesBy adopting multi-stage Docker builds, developers consistently cut image sizes down by 60–80%. For example, a full Node.js image that starts at nearly 800MB can be reduced to around 120–150MB simply by avoiding unnecessary dependencies and isolating build artifacts. This leads to:
In today’s container-first world, the size and structure of your images directly impact the performance of your entire system. Whether you're scaling microservices, deploying to serverless containers, or pushing images to a registry hundreds of times per day, optimizing your Docker builds becomes not just a best practice but a necessity.
Multi-stage builds ensure your production images are fast, lean, and secure—without changing a single line of your application code. It’s one of those rare optimizations that costs nothing to implement but provides massive returns.
Written by
devsafix@gmail.com