Skip to content
Go back

Week 6: Containerizing a Node.js Backend

Edit page

🐳 Docker 360 β€” Week 6 of 16 | Run Node.js in production like a pro

🎯 Learning Objective

By the end of this week, you will be able to write a production-grade Dockerfile for a Node.js backend: slim base image, reproducible installs with npm ci, running as a non-root user, proper SIGTERM handling for graceful shutdowns, and a /health endpoint wired to Docker’s HEALTHCHECK. Iska matlab ye hai ke β€” your API will start fast, stop cleanly, and tell the orchestrator when it’s actually ready.

🎨 Visual Diagrams

Production Dockerfile anatomy

 FROM node:22-slim              ◀── small, Debian-based, has what prod needs
   β”‚
   β”œβ”€ ENV NODE_ENV=production  ◀── faster Express, no dev warnings
   β”œβ”€ WORKDIR /app
   β”œβ”€ COPY package*.json ./
   β”œβ”€ RUN npm ci --omit=dev    ◀── reproducible, lockfile-exact install
   β”œβ”€ COPY --chown=node:node . .
   β”œβ”€ USER node                ◀── NEVER run as root in prod
   β”œβ”€ EXPOSE 3000
   β”œβ”€ HEALTHCHECK ...          ◀── Docker pings /health
   └─ CMD ["node","server.js"] ◀── exec form β†’ signals reach Node

Graceful shutdown: what happens on docker stop

 docker stop api
      β”‚
      β”‚  SIGTERM sent to PID 1 (node) ──▢ app finishes in-flight requests
      β–Ό                                   closes DB connections, then exits
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   10s grace (default)   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚ RUNNING  β”‚ ─────────────────────▢ β”‚  EXITED 0 β”‚  βœ… clean
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

 WITHOUT a SIGTERM handler (or with shell-form CMD):

 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   SIGTERM ignored/lost  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚ RUNNING  β”‚ ─────────────────────▢ β”‚ SIGKILL   β”‚  ❌ requests cut mid-flight
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    after 10s timeout   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   ❌ exit code 137

Iska matlab ye hai ke β€” graceful shutdown is the difference between β€œdeploy went fine” and β€œusers saw errors during the deploy”.

Health check lifecycle

 container starts
      β”‚
      β–Ό
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   HEALTHCHECK every 30s:  GET /health
 β”‚  starting  β”‚ ──────────────────────────▢ 200 OK β†’ healthy βœ…
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                               β”‚
                                              β–Ό non-200 / timeout
                                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                         β”‚unhealthyβ”‚ β†’ orchestrator restarts
                                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    or stops routing

🧠 Theory Deep Dive

npm ci vs npm install β€” reproducibility wins

npm installnpm ci
Readspackage.json (may update lockfile)package-lock.json only
node_modules handlingMerges/incrementalDeletes and reinstalls clean
Speed in CI/DockerSlowerFaster
Deterministic❌ Can driftβœ… Byte-identical every time

In Docker builds you always want npm ci --omit=dev: it installs exactly what the lockfile says, skips devDependencies, and fails loudly if package.json and the lockfile disagree β€” catching a real bug before it ships.

Why never run as root

If an attacker escapes your app (e.g., through a dependency vulnerability), running as root inside the container makes host escape dramatically easier. The official Node images ship with a ready-made node user (uid 1000). Two lines β€” USER node plus --chown on your copied files β€” close the biggest easy hole.

⚠️ Switch to USER node after the npm ci step if you need root-only operations (like installing OS packages), or keep installs rootless-friendly. Files copied as root won’t be writable by node β€” that’s why we use COPY --chown=node:node.

PID 1 and the signal problem

In a container, your CMD becomes PID 1. The Linux kernel treats PID 1 specially: it ignores SIGTERM unless the process explicitly handles it. Two rules follow:

  1. Use exec-form CMD (["node", "server.js"], not node server.js). Shell form wraps your app in /bin/sh, and the shell β€” not Node β€” gets the SIGTERM. Your handler never fires.
  2. Handle SIGTERM in code: close the HTTP server (stop accepting new connections, finish in-flight ones), release resources, then exit.

Node’s server.close() does exactly the graceful part: it stops accepting new connections but waits for existing ones to finish.

HEALTHCHECK β€” let Docker watch your app

HEALTHCHECK tells Docker how to probe your container. Unlike a simple β€œis the process alive” check, hitting /health proves the app can actually serve traffic. Orchestrators (and docker ps) use the healthy/unhealthy status to decide routing and restarts.

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "fetch('http://localhost:3000/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"

--start-period gives slow-starting apps a grace window before failures count. Iska matlab ye hai ke β€” no false β€œunhealthy” verdicts while your app is still booting.

πŸ’» Hands-On Lab

We will build a small Express API with a /health endpoint and graceful shutdown, containerize it production-style, and verify health + clean stops.

Step 1 β€” Scaffold the app

mkdir -p ~/docker360/week6/api && cd ~/docker360/week6/api
cat > package.json <<'EOF'
{
  "name": "week6-api",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": { "start": "node server.js" },
  "dependencies": { "express": "^4.21.2" }
}
EOF
cat > server.js <<'EOF'
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;

app.get("/health", (req, res) => res.json({ status: "ok", uptime: process.uptime() }));
app.get("/", (req, res) => res.send("🐳 Docker 360 β€” Week 6 API is running"));

const server = app.listen(PORT, () => console.log(`API listening on :${PORT}`));

// Graceful shutdown: finish in-flight requests, then exit
process.on("SIGTERM", () => {
  console.log("SIGTERM received β€” shutting down gracefully...");
  server.close(() => {
    console.log("All connections closed. Bye!");
    process.exit(0);
  });
  // Safety net: force exit if connections hang
  setTimeout(() => process.exit(1), 8000).unref();
});
EOF
ls

Step 2 β€” Generate the lockfile (needed for npm ci)

docker run --rm -v "$PWD":/app -w /app node:22-slim npm install --package-lock-only
ls package-lock.json

βœ… Expected result: package-lock.json exists β€” generated inside a container, no local Node needed.

Step 3 β€” Write the production Dockerfile

Create Dockerfile:

FROM node:22-slim

ENV NODE_ENV=production
WORKDIR /app

# Deps first for layer caching; lockfile-exact install, no devDeps
COPY package*.json ./
RUN npm ci --omit=dev

# App code owned by the non-root user
COPY --chown=node:node . .
USER node

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "fetch('http://localhost:3000/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"

# Exec form β†’ SIGTERM reaches Node directly
CMD ["node", "server.js"]

Also add a .dockerignore:

node_modules
.git
*.log

Step 4 β€” Build and run

docker build -t week6-api:1.0 .
docker run -d --name api -p 3000:3000 -e PORT=3000 week6-api:1.0
sleep 3
curl -s http://localhost:3000/health

βœ… Expected result: {"status":"ok","uptime":...} β€” the API is up and configurable via env var.

Step 5 β€” Verify the health status and non-root user

sleep 12
docker inspect api --format '{{.State.Health.Status}}'
docker exec api whoami

βœ… Expected result: healthy and node β€” Docker’s health check passes and the app runs as the non-root node user.

Step 6 β€” Prove the graceful shutdown works

# Start a slow request in the background (takes 5s to respond)
docker exec -d api node -e "setTimeout(()=>{},5000)" 2>/dev/null
time docker stop api
docker logs api --tail 5

βœ… Expected result: logs show SIGTERM received β€” shutting down gracefully... then All connections closed. Bye!, and docker stop completes in ~1s (not the full 10s timeout). Iska matlab ye hai ke β€” the app exited on its own terms instead of being SIGKILLed.

Compare with the ugly version: rebuild the image with shell-form CMD node server.js, run it, and docker stop will hang the full 10 seconds before exit code 137. Try it once β€” the difference sticks in memory.

Step 7 β€” Clean up

docker rm api
docker rmi week6-api:1.0

βœ… Checkpoint

Q1: Why is npm ci --omit=dev better than npm install in a production Dockerfile? A1: npm ci installs exactly what package-lock.json specifies (deterministic, faster in clean environments) and --omit=dev skips devDependencies, keeping the image lean. It also fails if the lockfile is out of sync β€” catching real issues early.

Q2: What breaks if you use shell-form CMD node server.js instead of exec form? A2: The shell (/bin/sh) becomes PID 1 and receives the SIGTERM, not Node. Your graceful-shutdown handler never runs, so docker stop hangs until the 10s timeout and ends with SIGKILL (exit 137).

Q3: Why run the container as USER node instead of root? A3: If the app is compromised, a non-root user limits what the attacker can do inside the container and makes container-escape to the host much harder. It’s two lines of config for a major security win.

Q4: What does HEALTHCHECK give you that β€œcontainer is running” doesn’t? A4: It proves the app actually serves traffic (via /health), not just that the process exists. Docker reports healthy/unhealthy, and orchestrators use it for routing decisions and automatic restarts.

πŸ”œ Next Week

Week 7: stateful services β€” running PostgreSQL in Docker with init scripts, named volumes, and real backup/restore drills.


Edit page
Share this post on:

Previous Post
Week 7: PostgreSQL in Production with Docker
Next Post
Week 5: Containerizing a React Frontend