Optimize Node.js Docker Images
Build minimal, secure, and fast Node.js Docker images for production using multi-stage builds and best practices.
Prerequisites
- -Docker installed
- -Existing Node.js project with package.json
Steps
Create an optimized multi-stage Dockerfile
Use multi-stage builds to separate the build environment from the production runtime, reducing final image size.
Use alpine images for smaller size. The multi-stage build ensures dev dependencies and source code are not in the final image.
Create .dockerignore to exclude unnecessary files
Prevent unnecessary files from being copied into the Docker build context, improving build speed and security.
Use npm ci instead of npm install
npm ci provides faster, reproducible installs by using the exact versions from package-lock.json.
npm ci deletes node_modules before installing, ensuring a clean state. It also fails if package-lock.json is out of sync.
Run as non-root user
Create and switch to a non-root user for security. Never run your application as root in a container.
If your app writes to the filesystem, ensure the nodejs user has write permissions to those directories.
Build and verify image size
Build the image and check that the final size is reasonable (typically 100-200MB for alpine Node.js apps).
Add a health check
Add a HEALTHCHECK instruction so orchestrators can monitor container health.
Use wget instead of curl in alpine images since wget is included by default but curl is not.
Full Script
FAQ
Discussion
Loading comments...