This repository demonstrates practical steps I used to reduce the size of Docker images for a Node.js application. The goal is to keep images small, secure, and fast to build and deploy.
In this repo I applied three main strategies:
- Exclude unnecessary files via
.dockerignore(e.g.node_modules,.git). - Use a smaller base image (Alpine-based runtime) where appropriate.
- Multistage builds to compile/build in a larger builder image but copy only the runtime artifacts into the final, minimal image.
These changes together often reduce image size by a large factor and speed up CI/CD and deployments.
-
Added a
.dockerignorefile that excludesnode_modules/,.git/, local environment files, editor files, and other build artifacts so they are never sent to the Docker daemon. -
Switched the final image to a small base (Alpine-based) to shrink the runtime image footprint.
-
Converted the Dockerfile to a multistage build:
builderstage uses a full Node image to install dependencies and build the app.runner(final) stage uses a minimal image and only copies the production build and runtime dependencies.
- Added a
.dockerignorefile to exclude unnecessary items such asnode_modules,.git, local environment files, build outputs, and editor/system files. - Switched to a lightweight Alpine-based image to reduce the final runtime size.
- Implemented multi‑stage builds so that dependencies and build tools exist only in the build stage, and only the final compiled output and production dependencies are included.
- Install production‑only dependencies.
- Remove package manager caches and temporary files.
- Use minimal base images or distroless when appropriate.
- Use caching properly to speed up builds.
- Build the image locally:
docker build -t myapp:latest . - Check size:
docker images | grep myapp. - Inspect layers:
docker history myapp:latestor usedive myapp:latest.
The final Docker image is significantly smaller, faster to build, and optimized for production deployment.