Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 111 ยท Language Recipes

Containerizing a Node.js App

Containerize a Node.js app the right way: a multi-stage Dockerfile with npm ci, a non-root user, a healthcheck, graceful shutdown and production settings.

Node.js is one of the easiest things to put in a container and one of the easiest to get subtly wrong. A five-line Dockerfile runs your app, but it also produces a 1.6 GB image that reinstalls all dependencies on every code change, runs as root, ships development tooling to production and ignores shutdown signals. This lesson builds the version you would be happy to deploy, one decision at a time, and measures each improvement.

The example is a tiny Express 5 API with a health endpoint. Every command and output below comes from building and running it on Docker 29 with the official Node.js 24 images. Where it applies, a note tells you what changes for a TypeScript or framework build.

The app

The project has three files that matter: package.json, a lock file (package-lock.json, created by npm install), and the source.

JSON
{
  "name": "hello-api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node src/server.js",
    "test": "node --test"
  },
  "dependencies": {
    "express": "^5.1.0"
  }
}
JavaScript
// src/server.js
import express from 'express';

const app = express();
const port = Number(process.env.PORT ?? 3000);

app.get('/', (req, res) => {
  res.json({ message: 'Hello from a container', env: process.env.NODE_ENV ?? 'unset' });
});

app.get('/healthz', (req, res) => {
  res.status(200).send('ok');
});

const server = app.listen(port, '0.0.0.0', () => {
  console.log(`listening on ${port} as uid ${process.getuid()}`);
});

function shutdown(signal) {
  console.log(`${signal} received, closing`);
  server.close(() => process.exit(0));
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

Two details of this code matter for containers. The server listens on 0.0.0.0, not localhost: inside a container, localhost is the container's own loopback, and a server bound to it cannot be reached through a published port. And it handles SIGTERM, which is the signal docker stop sends. We will come back to both.

The naive Dockerfile

This is what most tutorials show, and it is a useful baseline:

DOCKERFILE
FROM node:lts
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]

Build it and look at what you got:

CONSOLE
$ docker build -f Dockerfile.naive -t app-naive .
$ docker images app-naive
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
app-naive    latest    7d1e9c0b4a2f   20 seconds ago   1.64GB
$ docker run --rm app-naive id
uid=0(root) gid=0(root) groups=0(root)

The problems, in order of importance:

  1. 1.64 GB. node:lts is the full Debian-based image with compilers and many system tools your app never uses.
  2. Runs as root. A bug or a malicious dependency gets root inside the container (see Users and Permissions).
  3. COPY . . before npm install. Any code change invalidates the layer cache and reinstalls every package (The Build Cache).
  4. npm install may update versions instead of failing when package.json and the lock file disagree, and it installs dev dependencies.
  5. NODE_ENV is unset, so Express and many libraries run in their slower, more verbose development mode.
  6. CMD ["npm", "start"] makes npm PID 1 with your app as its child. Depending on the npm version and how the app is started, signals may not reach your code, and then docker stop ends in a forced kill.

Step 1: a .dockerignore

Before the Dockerfile, keep junk out of the build context. If your own node_modules (built for Windows or macOS, perhaps with native modules) were copied into the image, they could shadow the ones installed in the container:

TEXT
node_modules
npm-debug.log
.git
.env
Dockerfile

This also keeps .env out of the image, where it would be readable by anyone who can pull it. See Build Context and .dockerignore.

Step 2: the production Dockerfile

Here is the improved version. It uses two stages: deps installs production dependencies, and runtime is what you run.

DOCKERFILE
# syntax=docker/dockerfile:1
ARG NODE_VERSION=24

FROM node:${NODE_VERSION}-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci --omit=dev

FROM node:${NODE_VERSION}-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node package.json ./
COPY --chown=node:node src ./src
USER node
EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "src/server.js"]

Build it and compare:

CONSOLE
$ docker build -t app:1 .
$ docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}' | grep -E '^app'
app:1 249MB
app-naive:latest 1.64GB

From 1.64 GB to 249 MB, and the official node:24-alpine base alone is about 244 MB of that on this machine, so the app and its dependencies add only a few megabytes. Let us go through the choices.

node:24-alpine. The Alpine variant is far smaller than the Debian one. The trade-off is musl instead of glibc, which can break some native modules (packages with precompiled binaries that assume glibc, for instance). If an install fails on Alpine, switch to node:24-slim (Debian) and keep everything else. See Choosing a Base Image. Pin a major version with an ARG so upgrades are a conscious change; pin a full digest if you need reproducibility.

npm ci --omit=dev. npm ci installs exactly what the lock file says and fails if package.json and the lock file disagree, so builds are reproducible. --omit=dev leaves out test runners and linters. Commit the lock file; without it npm ci refuses to run.

The cache mount. --mount=type=cache,target=/root/.npm keeps npm's download cache outside the image. When one dependency changes, only that package is downloaded (Build Performance).

Copy the manifests first. package.json and package-lock.json are copied alone before the install. Edit your source and rebuild:

CONSOLE
$ echo "// tweak" >> src/server.js
$ docker build -t app:2 . --progress=plain
...
#8  [deps 3/4] COPY package.json package-lock.json ./
#8  CACHED
#9  [deps 4/4] RUN --mount=type=cache,target=/root/.npm     npm ci --omit=dev
#9  CACHED
#10 [runtime 3/5] COPY --from=deps --chown=node:node /app/node_modules ./node_modules
#10 CACHED
#13 [runtime 5/5] COPY --chown=node:node src ./src
#13 DONE 0.4s

The install is CACHED; only the final source copy ran.

USER node. The official Node images ship with an unprivileged user named node (UID 1000). --chown=node:node makes the copied files belong to it. Check the result:

CONSOLE
$ docker run -d --name api -p 127.0.0.1:3000:3000 app:1
$ docker exec api id
uid=1000(node) gid=1000(node) groups=1000(node)
$ docker exec api sh -c 'touch /app/x && echo writable'
touch: /app/x: Permission denied

The process is not root, and it cannot even write into its own application directory (/app was created by WORKDIR as root). That is a feature: an attacker who finds a code-execution bug cannot modify your code. If the app needs a writable folder (uploads, a cache), create it and give it to node explicitly, or use a volume.

NODE_ENV=production. It is set in the runtime stage only, after dependencies are installed. The app reports it:

CONSOLE
$ curl -s localhost:3000/
{"message":"Hello from a container","env":"production"}

Note that we did not set NODE_ENV=production before npm ci: we passed --omit=dev explicitly, which is clearer than relying on an environment variable.

CMD ["node", "src/server.js"]. In exec form, with node directly rather than npm start. Node is now PID 1:

CONSOLE
$ docker exec api ps
PID   USER     TIME  COMMAND
    1 node      0:00 {MainThread} node src/server.js
   33 node      0:00 ps

That makes signals work, which is the next topic.

Health checks

The HEALTHCHECK runs a tiny Node script that calls the app's own /healthz endpoint. It uses the fetch built into Node 18+, so the Alpine image needs neither curl nor wget. After a few seconds:

CONSOLE
$ docker ps --filter name=api --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
NAMES   STATUS                    PORTS
api     Up 10 seconds (healthy)   127.0.0.1:3000->3000/tcp

The status is only as good as the endpoint. Make /healthz cheap and decide deliberately whether it checks the database: if it does, a database outage marks every app container unhealthy, which may be right (a load balancer should stop sending traffic) or wrong (restart loops during a database blip). See HEALTHCHECK.

Graceful shutdown

When you run docker stop, Docker sends SIGTERM to PID 1 and waits (10 seconds by default) before sending SIGKILL. Our app listens for SIGTERM, stops accepting connections and exits:

CONSOLE
$ time docker stop api
api

real    0m1.419s
$ docker logs api
listening on 3000 as uid 1000
SIGTERM received, closing

Done in about a second. Now compare it with a Node process that has no signal handler, started as PID 1. Linux does not apply the default "terminate" action to PID 1, so an unhandled SIGTERM is simply ignored:

CONSOLE
$ docker run -d --name nosig node:24-alpine node -e "setInterval(()=>{},1000)"
$ time docker stop -t 10 nosig
nosig

real    0m10.7s
$ docker inspect -f '{{.State.ExitCode}}' nosig
137

It hung for the full ten seconds and ended with exit code 137 (128 + 9: killed by SIGKILL). Any in-flight requests were cut off. The fixes, in order of preference: handle SIGTERM in your code as shown; or run with --init (Compose: init: true), which puts a tiny init process in front:

CONSOLE
$ docker run -d --init --name nosig2 node:24-alpine node -e "setInterval(()=>{},1000)"
$ time docker stop -t 10 nosig2
nosig2

real    0m1.6s
$ docker inspect -f '{{.State.ExitCode}}' nosig2
143

With --init the process ended in 1.6 seconds with exit code 143 (128 + 15: terminated by SIGTERM). Both techniques are explained in Signals, PID 1 and --init and CMD and ENTRYPOINT.

A build step: TypeScript and frameworks

If your app compiles (TypeScript, Next.js, NestJS), add a middle stage that has the dev dependencies and produces the build output, and copy only that output into the runtime stage. This is a read-only sketch, assuming a build script that writes to dist/:

DOCKERFILE
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build

FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

FROM node:24-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps  --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
CMD ["node", "dist/server.js"]

The compiler and type definitions stay in the build stage and never reach production. Since deps and build do not depend on each other, BuildKit runs them in parallel (Multi-Stage Builds). Node 24 can also run .ts files directly in some cases by stripping types, but a compiled build is still the safer production default.

Development with Compose

For local development you usually do not want to rebuild on every change. Use a bind mount of the source and a watch mode, keeping node_modules from the image so the host's copy does not interfere. A read-only sketch (see Compose for Development):

YAML
services:
  api:
    build: .
    command: node --watch src/server.js
    ports:
      - "127.0.0.1:3000:3000"
    volumes:
      - ./src:/app/src
    environment:
      NODE_ENV: development

The production image and the development setup share one Dockerfile, which is the whole point of containers.

Production settings checklist

  • Memory: Node sizes its heap from the container's memory limit in recent versions, but you can cap it explicitly with NODE_OPTIONS=--max-old-space-size=384 when the container limit is 512 MB, leaving room for buffers and native memory (Resource Limits).
  • One process per container: run clustering with several containers behind a proxy, not with cluster inside one.
  • Logs to stdout/stderr: do not write log files in the container; Docker collects the output (Logs and exec).
  • Config from the environment: read process.env and pass values at run time (Configuring Containers). Never bake secrets into the image.
  • Pin and update: pin the Node major, rebuild regularly for security patches, and scan the image (Image Security and Scanning).
  • Lock file in Git: npm ci needs it, and it is what makes two builds produce the same dependencies.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the production Dockerfile copy package.json and package-lock.json before the source code?

    The install layer depends only on the manifests. If they are unchanged, Docker reuses the CACHED layer even after you edit source files.
  2. 2. What is the main difference between npm install and npm ci --omit=dev for an image build?

    npm ci is the reproducible, CI-friendly install. Combined with --omit=dev the production image contains only the packages the app needs at run time.
  3. 3. A Node server in a container is started as PID 1 with no SIGTERM handler. What does docker stop -t 10 do?

    PID 1 does not get the default SIGTERM action, so the signal is ignored until the timeout passes. In the test it took 10.7 seconds and exited with 137. Handle the signal in code or run with --init.
  4. 4. Why does the server listen on 0.0.0.0 instead of localhost in a container?

    Published ports forward traffic to the container's network interface. A server bound only to the loopback address does not accept those connections.
  5. 5. You switch the base image from node:24-alpine to node:24-slim. When is that a good idea?

    Alpine uses musl libc; some prebuilt native modules assume glibc. The Debian-based slim image is larger but more compatible, and the rest of the Dockerfile stays the same.

Summary

  • A naive node:lts image with COPY . . and npm install was 1.64 GB and ran as root; the multi-stage Alpine version was 249 MB with a non-root user.
  • Add a .dockerignore (node_modules, .git, .env), copy the manifests first, and use npm ci --omit=dev with a cache mount.
  • Set NODE_ENV=production in the runtime stage, run as USER node with --chown=node:node, and run node directly (not npm start).
  • Listen on 0.0.0.0, add a HEALTHCHECK that uses Node's built-in fetch, and handle SIGTERM (or use --init): without it docker stop waited 10.7 seconds and exited with code 137.
  • For TypeScript or framework builds, add a build stage and copy only the output into the runtime stage.
  • Use Compose bind mounts and node --watch for development, keep config in environment variables and logs on stdout.

Next: Containerizing a Python App