Skip to content
M

Docker for Node.js Developers: From Dockerfile to Production

Write a small, secure Node.js Docker image with multi-stage builds, layer caching and docker compose for local development.

Md. Nazim Uddin

Updated Oct 25, 20262 min read0 views

Share
Docker for Node.js Developers: From Dockerfile to Production
On this page

Docker removes the "works on my machine" problem. A good image is small, fast to build and safe to run.

A multi-stage Dockerfile

FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]

The first stage has all build tools. The final image keeps only compiled code and production dependencies, so it is much smaller.

Order matters for caching

Copy package.json and install dependencies before copying the rest of the code. Docker reuses the cached install layer until your dependencies actually change.

Add a .dockerignore

Exclude node_modules, .git, .env and build output. It speeds up builds and keeps secrets out of the image.

Do not run as root

The USER node line drops privileges. If the app is ever compromised, the attacker has far fewer rights.

Compose for local development

services:
  api:
    build: .
    ports: ["5000:5000"]
    env_file: .env
    depends_on: [db]
  db:
    image: postgres:16
    volumes: [pgdata:/var/lib/postgresql/data]
volumes:
  pgdata:

One command, docker compose up, starts the whole stack.

Health checks

Add a /health endpoint and a container health check so orchestrators can restart a stuck instance.

Takeaway

Multi-stage builds, smart layer ordering, a non-root user and a compose file get you a clean, reproducible setup.

Keep reading

NestJS REST API Best Practices That Scale
Backend
2 min read0

NestJS REST API Best Practices That Scale

Module boundaries, DTO validation, guards, exception filters and configuration: the NestJS structure that stays clean as your API grows.

NestJSTypeScriptNode.js
MNMd. Nazim UddinRead