Skip to the page

Docker for Node and Next.js apps · mid

Running Node correctly in a container

In a container, start node directly in exec form (or behind a tiny init such as tini via docker run --init), run as the non-root node user with NODE_ENV=production, log to stdout, handle SIGTERM for graceful shutdown, and keep the V8 heap limit below the container's memory limit.

The notes

What you must know

  • Node is not designed to run as PID 1: it will not respond to SIGINT/SIGTERM the way you expect. Use docker run --init (tini) or add tini to the image, and handle SIGTERM in your code.
  • CMD ["node", "server.js"], not npm start: npm adds a process and can swallow signals (the official docker-node guide says so).
  • USER node (uid 1000) in official images; NODE_ENV=production for frameworks that change behaviour.
  • Set memory limits on the container; keep --max-old-space-size (or --max-old-space-size-percentage) below the limit so V8 garbage-collects before the kernel kills the process (OOMKilled).
  • One main process per container; scale with more containers, not cluster mode inside one, on orchestrators.
  • Logs go to stdout/stderr; the platform collects them. Health: an HTTP endpoint for the orchestrator's liveness/readiness checks (Docker's HEALTHCHECK is optional).
  • Listen on 0.0.0.0 inside the container (not 127.0.0.1), or the published port cannot reach the app.

The red pen

Common traps: mistake → fix

  • Mistake: Listening on localhost inside the container is fine

    Fix: the published port forwards to the container's interface; bind to 0.0.0.0.

  • Mistake: Docker restarts my app gracefully by default

    Fix: without SIGTERM handling, docker stop waits 10 s and then kills the process.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why does Ctrl-C not stop your Node container?
  2. How do you run Node in production containers: user, command, environment?
  3. The container is OOMKilled under load but the heap looks fine locally. What do you check?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview