Docker for Node.js apps
Overview
“It works on my machine” stops being a problem when you ship the machine. A container image packages a specific Node version, your dependencies and your code into one artifact. The same image runs on your laptop, in CI and in production — on almost every hosting platform.
You’ll write a production-quality Dockerfile for the courses API and a Compose file to run it with Postgres and Redis locally. (You need Docker Desktop or Docker Engine installed.)
Images, containers and layers
- An image is a read-only template: a filesystem plus a start command.
- A container is a running instance of an image.
- A Dockerfile describes how to build an image, one instruction at a time. Each instruction creates a layer, and Docker caches layers: if an instruction and its inputs haven’t changed, Docker reuses the cached layer instead of running it again.
That caching is why instruction order matters so much.
A first Dockerfile — and why it’s slow
FROM node:26-slim
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "src/server.js"]It works, but COPY . . copies everything — so changing one line of source code invalidates the cache, and npm ci reinstalls every dependency on every build. It also includes dev dependencies, and runs as root.
A production Dockerfile
# syntax=docker/dockerfile:1
# ---- Stage 1: install production dependencies ----
FROM node:26-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
# ---- Stage 2: the image we actually ship ----
FROM node:26-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
COPY src ./src
USER node
EXPOSE 3000
CMD ["node", "src/server.js"]What each choice does:
- Pin the Node version (
node:26-slim) so builds are reproducible — the course targets Node 26 LTS.-slimimages are Debian-based and much smaller than the full image, while still compatible with most native modules. (Alpine images are smaller still, but use a different C library, which occasionally breaks native packages.) - Copy package files first, then
npm ci, then source code. Now editingsrc/only rebuilds the last layers; dependencies come from cache untilpackage-lock.jsonchanges. npm ci --omit=devinstalls exactly what the lockfile says, without test tools or linters.- Multi-stage build: only the final stage becomes the image. If you needed build tools (
python3,g++for native modules) or a TypeScript compile step, they’d live in an earlier stage and never ship. USER node— official Node images include a non-rootnodeuser. If an attacker exploits your app, they don’t get root inside the container.- Exec-form
CMD(["node", …]) makes Node the main process, so it receivesSIGTERMdirectly and your graceful shutdown code runs. Don’t start withnpm start.
If your app uses TypeScript, add a build stage:
FROM node:26-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build # outputs to dist/
# …final stage copies /app/dist instead of src.dockerignore
Like .gitignore, for the build context. Without it, COPY may send your local node_modules (built for your OS), .env secrets and .git history into the image:
node_modules
.env
.env.*
.git
coverage
*.log
Dockerfile
docker-compose.ymlBuild and run
docker build -t courses-api .
docker run --rm -p 3000:3000 \
-e DATABASE_URL=postgres://… \
-e JWT_SECRET=… \
courses-api-p 3000:3000 maps the container’s port to your machine. Configuration comes from environment variables at run time — exactly what Environment and configuration prepared you for. Never put secrets in the Dockerfile (ENV JWT_SECRET=…) or copy .env into the image: anyone with the image can read every layer.
Your app must listen on 0.0.0.0 (all interfaces), not 127.0.0.1 — inside a container, localhost is only reachable from the container itself. Express’s app.listen(port) already listens on all interfaces.
Docker Compose for local development
Your API needs Postgres and Redis. Docker Compose starts all of them with one command:
# docker-compose.yml
services:
api:
build: .
ports: ['3000:3000']
environment:
DATABASE_URL: postgres://app:app@db:5432/app
REDIS_URL: redis://redis:6379
JWT_SECRET: dev-only-secret-change-me
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
db:
image: postgres:18
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: app
volumes: ['pgdata:/var/lib/postgresql']
healthcheck:
test: ['CMD', 'pg_isready', '-U', 'app']
interval: 5s
redis:
image: redis:8
volumes:
pgdata:docker compose up --build # start everything
docker compose exec api node scripts/migrate.js
docker compose down # stop (add -v to delete the database volume)Services reach each other by service name — db and redis — on a private network Compose creates. The named volume keeps database data between restarts.
Many developers run only db and redis in Compose (docker compose up db redis) and run the API itself with node --watch on their machine, for the fastest edit-reload loop.
Image hygiene
- Scan images for known vulnerabilities (
docker scout cves courses-api, Trivy, or your registry’s scanner), and rebuild regularly to pick up patched base images. - Tag images with the Git commit (
courses-api:3f9c2e1), not justlatest, so you know exactly what’s deployed and can roll back. - Add a
HEALTHCHECKonly if your platform uses Docker’s own health status; Kubernetes and most hosts use their own HTTP checks against/livezand/readyzinstead.
Check the size.
docker images courses-api— a slim Node API image is typically 200–300 MB. If yours is over a gigabyte, look for dev dependencies, build tools or a missing.dockerignore.
Containerise the courses API
Write a multi-stage Dockerfile for the courses API: a deps stage that installs production dependencies with npm ci --omit=dev, and a final stage based on node:26-slim that copies node_modules and src, sets NODE_ENV=production, runs as the non-root node user, exposes port 3000 and starts Node directly. Add a .dockerignore that keeps node_modules, .env and .git out of the build.
# syntax=docker/dockerfile:1
FROM node:26-slim AS deps
# your code here# syntax=docker/dockerfile:1
FROM node:26-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM node:26-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
COPY src ./src
USER node
EXPOSE 3000
CMD ["node", "src/server.js"]
# .dockerignore
# node_modules
# .env
# .env.*
# .git
# coverage
# *.logSummary
- A container image bundles Node, your dependencies and your code, so it runs the same everywhere.
- Copy package files and install before copying source code, so dependency layers are cached.
- Multi-stage builds keep compilers and dev dependencies out of the final image.
- Run as the non-root
nodeuser, start Node directly with exec-formCMD, and never bake secrets into images. - Docker Compose runs the API with Postgres and Redis locally with one command.