What are key Dockerfile steps for Node.js Express apps?
Docker containerization fundamentals for Node.js.
use lightweight base image, copy app, install deps, expose port, set NODE_ENV, run.
BASE IMAGE SELECTION
Start with a lightweight node image, typically node:alpine or node:lts-slim. Alpine is the smallest, around 150MB. The full Ubuntu-based image is 900MB+. Unless you need system packages, Alpine is preferred. Use a major version tag like node:20-alpine to ensure consistency across rebuilds.
WORKDIR AND COPYING
Set a working directory: WORKDIR /app. Copy only package.json initially: COPY package*.json ./. This allows Docker to cache the dependency layer; if only app code changes, dependencies are not reinstalled. Install dependencies: RUN npm ci (use ci instead of install for exact versions). Then copy the rest: COPY . .. This ordering optimizes build cache.
EXPOSE AND ENV
EXPOSE the port your app listens on: EXPOSE 3000. Set NODE_ENV for production optimizations: ENV NODE_ENV=production. This ensures Express caching and logging optimizations are enabled automatically.
START COMMAND
Define the startup command: CMD ["node", "server.js"]. Alternatively, if using PM2, use CMD ["pm2-runtime", "start", "app.js"] for proper signal handling in containers. The process must run in the foreground (not daemonized) so Docker can supervise it.
USER PERMISSIONS
Create a non-root user for security: RUN useradd -m nodeuser && chown -R nodeuser /app. Then switch: USER nodeuser. This prevents container escapes from gaining root access on the host.
HEALTHCHECK OPTIONAL
Add a healthcheck so orchestrators know if the app is running: HEALTHCHECK --interval=10s --timeout=3s CMD curl -f http://localhost:3000/health || exit 1. This allows Kubernetes or Swarm to restart unhealthy containers.
EXAMPLE DOCKERFILE
FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . EXPOSE 3000 ENV NODE_ENV=production USER node CMD ["node", "server.js"]
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.