How to dockerize a Node.js application
· Category: Node.js
Short answer
Write a Dockerfile that uses a slim Node image, copies your application, installs dependencies, and starts the server.
Steps
- Create a Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
- Build the image:
docker build -t my-app .. - Run the container:
docker run -p 3000:3000 --env-file .env my-app. - Use
.dockerignoreto exclude node_modules and logs. - Prefer
npm ciovernpm installfor reproducible builds.
Tips
- Use multi-stage builds to reduce final image size by separating build dependencies from runtime.
- Run containers as a non-root user for security.
Common issues
- Copying the entire project before installing dependencies invalidates the Docker layer cache on every code change.
- Hardcoded ports inside containers conflict when running multiple instances on the same host.