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

  1. Create a Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
  1. Build the image: docker build -t my-app ..
  2. Run the container: docker run -p 3000:3000 --env-file .env my-app.
  3. Use .dockerignore to exclude node_modules and logs.
  4. Prefer npm ci over npm install for 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.