Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 133 ยท Production Node.js

Node.js in Docker and CI

Package a Node.js app in a small, secure Docker image with multi-stage builds, add a health endpoint, and run tests and builds in a CI pipeline with caching.

"It works on my machine" is the oldest deployment problem. A container image solves it by bundling your code, the Node.js runtime and the system libraries into one artifact that runs the same way on a laptop, in a test pipeline and on a server. Continuous integration (CI) complements it: every push automatically installs, tests and builds the project in a clean environment, so a broken change is found in minutes instead of after a deploy.

This lesson shows a production-quality setup for a Node.js 24 service: a multi-stage Dockerfile, a .dockerignore, the Node settings that matter inside containers, a health endpoint you can run right here, and a CI workflow. The Docker and CI files are read-only examples, because a browser cannot run a Docker daemon; the health endpoint is a live example. For deeper Docker knowledge, see the Docker tutorial and its Node recipe; for the Node side of shutdown and health, see Graceful Shutdown and Health Checks.

What goes into an image

An image is built in layers, one per Dockerfile instruction. Docker caches each layer and reuses it if the instruction and its inputs did not change. That has one big consequence for Node projects: copy the files that describe your dependencies (package.json, the lock file) first, install, and only then copy your source code. Your code changes on every commit, but your dependencies rarely do, so the slow npm ci layer stays cached.

flowchart TB
  A["Base image: node:24-slim"] --> B["Copy package.json + lockfile"]
  B --> C["npm ci  (cached until dependencies change)"]
  C --> D["Copy source code"]
  D --> E["Build step (tsc, bundler)"]
  E --> F["Final image"]

Layer order matters: stable inputs first, frequently changing files last.

A multi-stage Dockerfile

A build needs tools (TypeScript, bundlers, test frameworks) that a running server does not. A multi-stage build uses one stage to build and a second, clean stage that copies only the results. The final image is smaller, has less to attack, and starts faster to pull.

DOCKERFILE
# syntax=docker/dockerfile:1

# ---------- Stage 1: install all dependencies and build ----------
FROM node:24-slim AS build
WORKDIR /app

COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

COPY . .
RUN npm run build            # for example: tsc -> dist/

# ---------- Stage 2: production-only dependencies ----------
FROM node:24-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

# ---------- Stage 3: the runtime image ----------
FROM node:24-slim 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
EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --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", "dist/server.js"]

Go through the important choices:

  • A pinned, small base image. node:24-slim is Debian-based and a good default. -alpine images are smaller but use musl instead of glibc, which breaks some native add-ons. In production, pin the exact tag (and ideally the digest) so a rebuild next month gives the same result.
  • npm ci, not npm install. It installs exactly what the lock file says and fails if package.json and the lock file disagree. That is the reproducibility you want in an image and in CI.
  • --omit=dev in the deps stage leaves the test and build tools out of the runtime image.
  • USER node. The official images ship a non-root node user. If an attacker finds a bug in your app, they should not be root inside the container.
  • CMD ["node", "dist/server.js"] in exec form (a JSON array). Node becomes the container's main process (PID 1) and receives SIGTERM directly when the container is stopped. The shell form (CMD node dist/server.js) wraps it in /bin/sh, which may not forward the signal, so your graceful shutdown code would never run and the orchestrator would kill you after the timeout. Likewise, avoid CMD ["npm", "start"] for the same reason.
  • NODE_ENV=production is read by many libraries (and by Express) to switch off development behavior and enable optimizations.

If the app has no build step (plain JavaScript), skip the build stage and copy the source into the runtime stage next to the production node_modules.

Keep the build context small

Docker sends your project folder to the builder as the build context. A .dockerignore file keeps junk out, which makes builds faster and prevents secrets from ending up in an image:

TEXT
node_modules
dist
.git
.env
.env.*
*.log
coverage
Dockerfile
docker-compose*.yml

Never bake secrets into an image (COPY .env, or ENV API_KEY=...). Anyone who can pull the image can read its layers. Pass configuration when the container starts instead, as covered in Secrets and Configuration:

Terminal
docker run --rm -p 3000:3000 --env-file .env.production my-service:1.4.0

Running Node well inside a container

Containers bring a few runtime details that matter:

  • Memory limits. When a container is limited to, say, 512 MB, V8 may not know it should keep its heap smaller. Recent Node versions detect cgroup limits and size the heap sensibly, but you can be explicit: node --max-old-space-size=384 dist/server.js, leaving headroom for buffers, the stack and native memory. See V8 and Memory.
  • CPU count. One Node process uses one main thread. Scale with more container replicas (preferred) rather than the cluster module inside a container; see Cluster and Scaling.
  • Logs. Write one JSON line per event to standard output and let the platform collect it. Do not write log files inside the container; they vanish with it. See Logging.
  • Signals. Handle SIGTERM by draining connections before exiting, and make your shutdown timeout shorter than the platform's grace period (10 seconds by default for docker stop, 30 for Kubernetes).
  • Read-only file system. You can run with --read-only and give the app a writable tmpfs for temporary files; this blocks many attacks that need to write to disk.

Health checks: liveness and readiness

Orchestrators need to ask your service two different questions:

  • Liveness: "Is the process stuck beyond repair?" If not, restart it. This check must be cheap and must not depend on other services, otherwise a database outage makes every instance restart in a loop.
  • Readiness: "Can you take traffic right now?" Fail it while starting, while shutting down, or when a required dependency is unreachable; the load balancer then stops sending requests but does not kill the process.

Here is a service with both endpoints. It reports not-ready during start-up (while a fake database connection is opening) and again once shutdown begins. The client plays the role of an orchestrator probing it.

Node.js Liveness and readiness endpoints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Liveness stays 200 the whole time, while readiness goes up and down. During shutdown the service first fails readiness so the load balancer removes it, then finishes in-flight requests, then exits.

In Compose or Kubernetes you point the platform at these URLs. Compose uses the healthcheck: key (see Docker health checks); Kubernetes uses livenessProbe and readinessProbe. The image above uses the built-in fetch for its HEALTHCHECK, so no curl is needed in the slim image.

A CI pipeline

A CI pipeline is a recipe that a server runs on every push and pull request. For Node it is nearly always: check out the code, install Node, install dependencies from the lock file, lint, type-check, test, build, and (on the main branch) build and push the image. Here is a workflow for GitHub Actions; other systems (GitLab CI, CircleCI, Jenkins) use the same steps in a different syntax.

YAML
name: ci

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node: [22, 24]
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
          cache: npm

      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm test
      - run: npm run build

  image:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
flowchart LR
  P["git push / pull request"] --> T["test job<br/>(Node 22 and 24)"]
  T --> L["lint + typecheck"]
  L --> U["unit + integration tests"]
  U --> B["build"]
  B -->|"main branch only"| I["build and push image"]
  I --> D["deploy"]

A typical Node pipeline: fast checks first, expensive image work only after everything passes.

Why it looks the way it does:

  • npm ci plus the setup-node cache. The npm download cache is restored between runs, so installs take seconds. Never cache node_modules itself across Node versions.
  • A version matrix. Testing on the Node versions you support (the current LTS and the previous one) catches version-specific breakage early. Node's built-in test runner (node --test, see The Test Runner) needs no extra dependency.
  • Order by speed. Lint and type-check fail in seconds; run them before the slow integration tests so developers get feedback quickly.
  • permissions: with the least privilege. A workflow that only reads code should get a read-only token. Grant packages: write only to the job that pushes.
  • Immutable tags. Tag images with the commit SHA (or a version number), never only latest; then every deploy is traceable and a rollback means deploying the previous tag.
  • Secrets stay in the CI secret store. They are injected as environment variables and masked in logs. Do not echo them, and do not pass them to pull requests from forks.

Finish the loop with two safety nets: run npm audit --omit=dev (or an equivalent scanner) in CI to catch known vulnerable dependencies, and scan the built image. Both are described in Deployment, along with process managers, reverse proxies and zero-downtime releases.

Common mistakes

  • Copying the whole project before npm ci, which invalidates the dependency cache on every commit.
  • Using CMD npm start or the shell form, so SIGTERM never reaches Node.
  • Running as root, or shipping .env files and .git inside the image.
  • Using latest tags for the base image or for your own releases.
  • Making the liveness check depend on the database, causing restart storms during a database outage.
  • Running the tests only on your laptop's Node version, then deploying on another.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why copy package.json and the lock file before the rest of the source in a Dockerfile?

    Docker reuses a layer when its inputs are unchanged. Dependencies change rarely and code changes constantly, so installing dependencies in an earlier layer saves a slow npm ci on most builds.
  2. 2. What is the main benefit of a multi-stage build for a Node.js service?

    Build tools and dev dependencies stay in an earlier stage. The runtime stage copies only compiled output and production dependencies, giving a smaller and safer image.
  3. 3. Why should a Dockerfile use CMD ["node", "server.js"] instead of CMD node server.js?

    The shell form starts /bin/sh as PID 1, which may not forward signals. With the exec form, Node gets the termination signal and can drain connections.
  4. 4. Which condition should make a readiness check fail but NOT a liveness check?

    A missing dependency means the instance should stop receiving traffic, but restarting it would not help. Liveness is reserved for states where only a restart fixes the problem.
  5. 5. Why does a CI workflow use npm ci instead of npm install?

    Reproducible installs are the point of CI. npm ci never updates the lock file and stops with an error when it is out of sync.

Summary

  • Order Dockerfile instructions from stable to changing: dependency files, npm ci, then source; use .dockerignore to keep the context small and secrets out.
  • Use a multi-stage build with npm ci --omit=dev for the runtime stage, a slim pinned base image and USER node.
  • Start Node with the exec-form CMD so it receives SIGTERM; configure secrets at run time, log to standard output, and scale with replicas.
  • Expose a cheap liveness endpoint and a dependency-aware readiness endpoint, and fail readiness before shutting down.
  • CI should install with npm ci, run lint, type-check, tests and build across supported Node versions, cache downloads, use least-privilege tokens and push images tagged with the commit.

Next: Project: Command-Line To-Do App