Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 133 ยท Frameworks and Ecosystem

Deploying Node.js Applications

Learn how to deploy Node.js apps - twelve-factor config, Docker multi-stage builds, systemd and PM2, health checks, graceful shutdown, reverse proxies, serverless and zero-downtime releases.

Writing an application that works on your machine is half the job. Deployment is the other half: getting it onto a server, starting it, keeping it running, updating it without users noticing, and finding out what happened when something goes wrong. Node.js is easy to run (node server.js) and that simplicity hides a number of decisions that decide whether your service is reliable.

This lesson walks through those decisions in order: how the app should be configured and behave so that any platform can run it, the common ways to run it (containers, process managers, serverless), how a reverse proxy fits in, and how to release new versions safely. The shutdown and proxy examples are runnable; the Dockerfile and the service files are read-only, because the editor has no Docker or systemd.

Build an app that is easy to deploy

Most deployment pain is solved before deployment, by how the app is written. The widely used twelve-factor guidelines boil down to a few habits that matter for Node.js:

  • Configuration comes from the environment. The same build runs in development, staging and production; only environment variables differ (PORT, DATABASE_URL, NODE_ENV, LOG_LEVEL). Never commit secrets. See Secrets and Configuration.
  • Processes are stateless. Do not keep sessions, uploaded files or caches in the memory or disk of one process if the next request might hit another instance. Put state in a database, Redis, or object storage.
  • Logs go to stdout. Let the platform collect them. See Logging and Observability.
  • Start fast, stop gracefully. Platforms start and stop instances all the time.
  • Dev and production look alike. Same Node.js major version, same OS family.

A first rule specific to Node is NODE_ENV=production. Many libraries (Express among them) switch to faster, quieter code paths when it is set. It also tells npm install to skip dev dependencies in some setups. Treat it as a flag your own code can read once, in the config module, and nowhere else.

Node.js Config from the environment, with safe defaults

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.

Notice 0.0.0.0: inside a container, listening only on 127.0.0.1 means nothing outside the container can reach you, a very common first-deployment mistake.

Where can a Node.js app run?

There are four common styles, from most control to least:

  1. A virtual machine you manage yourself (a VPS, an EC2 instance): you install Node, copy the code, run it under a process manager, put Nginx in front.
  2. A container (Docker) on a platform such as Kubernetes, ECS, Fly.io, Cloud Run or a PaaS: you package everything in an image, and the platform runs copies of it.
  3. A PaaS that builds for you (Heroku-style): you push code, it detects Node.js, runs npm install and npm start.
  4. Serverless functions (AWS Lambda, Vercel, Cloudflare Workers): you provide a handler function; the platform runs it on demand.

Containers are the most portable and are the default answer for services today, so we start there.

Docker: a multi-stage image

A Docker image is a snapshot of a file system plus a start command. For Node.js the aim is a small image that contains only what production needs: the Node runtime, production dependencies and your built code. A multi-stage build achieves it: an early stage installs everything and builds, and the final stage copies only the results.

DOCKERFILE
# Read-only: you run `docker build` on your machine, not in our editor.

# ---- Stage 1: install all dependencies and build ----
FROM node:24-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

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

# ---- Stage 3: the final, small image ----
FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package.json ./
USER node
EXPOSE 3000
CMD ["node", "--enable-source-maps", "dist/server.mjs"]

Why each line is the way it is:

  • COPY package*.json before COPY . .: Docker caches each step. Dependencies change rarely, code changes constantly. By copying the manifest first and installing, the slow npm ci layer is reused until package-lock.json changes.
  • npm ci, not npm install: it installs exactly what the lock file says and fails if the files disagree, so builds are reproducible.
  • --omit=dev: test frameworks, compilers and type packages do not belong in production.
  • USER node: the official image includes an unprivileged user. Do not run your server as root.
  • CMD ["node", ...] in exec form (a JSON array) starts Node as the main process, so it receives the stop signal directly. Writing CMD npm start puts a shell and npm in between, and SIGTERM often never reaches your program. This is one of the most common causes of slow, ugly shutdowns.
  • A .dockerignore with node_modules, .git, .env and dist keeps the build context small and keeps secrets out of the image.

Pin the base image to a major version at least (node:24-slim), and rebuild regularly to receive security fixes. Alpine-based images are smaller but use a different C library (musl), which can break packages with native addons; slim (Debian) is the safer default.

Process managers: systemd and PM2

On a plain server you need something that starts your app at boot and restarts it if it crashes. Never leave node server.js running in a terminal. Two options:

systemd is built into most Linux distributions. You describe the service in a unit file:

INI
# /etc/systemd/system/myapp.service   (read-only example)
[Unit]
Description=My Node.js app
After=network.target

[Service]
Type=simple
User=myapp
WorkingDirectory=/srv/myapp
EnvironmentFile=/etc/myapp.env
ExecStart=/usr/bin/node --enable-source-maps dist/server.mjs
Restart=on-failure
RestartSec=2
TimeoutStopSec=15

[Install]
WantedBy=multi-user.target

You then run systemctl enable --now myapp and read logs with journalctl -u myapp -f. systemd sends SIGTERM on stop and SIGKILL after TimeoutStopSec.

PM2 is a Node-specific process manager. It can restart on crash, run several instances in cluster mode (see Clustering and Scaling), and rotate logs:

Terminal
# Read-only: commands for your own server.
npm install --global pm2
pm2 start dist/server.mjs --name myapp -i max   # one worker per CPU core
pm2 save && pm2 startup                         # restart on reboot
pm2 reload myapp                                # zero-downtime restart

Use PM2 when you deploy to bare servers and want its conveniences. In containers do not use PM2 inside the image: the platform (Kubernetes, ECS and similar) already restarts failed containers, and a process manager inside hides crashes from it. Run one Node process per container and scale by adding containers.

Graceful shutdown

Whenever you deploy, scale down or restart, the platform asks your process to stop by sending SIGTERM, and sends SIGKILL (which cannot be caught) after a grace period, often 10 to 30 seconds. If your process just dies, requests in flight are cut off: users see errors during every deploy.

A graceful shutdown does this:

  1. On SIGTERM, stop accepting new connections (server.close()).
  2. Let requests already in progress finish.
  3. Close other resources: database pool, queues, timers.
  4. Exit with code 0. If it takes too long, force an exit.

Also report "not ready" on your readiness endpoint as soon as shutdown begins, so the load balancer stops sending traffic first. The next example runs the whole sequence: a slow request is in flight, we send ourselves SIGTERM, and the request still completes. (The signal is delivered to our own process; in the editor this works because it runs on Linux.)

Node.js Graceful shutdown with a request in flight

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.

Look at the output: the signal arrives first, and "server closed" is only reported after the slow request has been answered (the close callback waits for it); the caller then prints what it received, which is the full response, not an error. A real program would also set a safety timer, for example setTimeout(() => process.exit(1), 10_000).unref(), in case something never finishes. The next lesson in the production chapter, Graceful Shutdown and Health Checks, goes deeper into WebSockets, databases and AbortSignal.

Do not call process.exit() as the first thing in a signal handler. It stops the process immediately, discarding pending work and unflushed output. Let the event loop drain, and set process.exitCode if you need a specific code.

Health checks

Platforms need to know whether an instance is alive and whether it should receive traffic: /healthz for liveness, /readyz for readiness, as shown in Logging and Observability. In a Dockerfile you can declare one with HEALTHCHECK, but orchestrators like Kubernetes use their own probe configuration, which is more flexible. A slow startup (loading a large cache, running migrations) is exactly what a startup probe or readiness check is for.

Reverse proxies

You almost never expose a Node.js process directly to the internet. A reverse proxy (Nginx, Caddy, HAProxy, a cloud load balancer, Cloudflare) sits in front and does the jobs it does best:

  • terminates TLS (HTTPS) and renews certificates,
  • serves static files and caches responses,
  • compresses responses and limits request sizes,
  • balances load across several instances and removes unhealthy ones,
  • absorbs slow clients, so your event loop does not wait on them.

A minimal Nginx configuration (read-only):

NGINX
upstream app {
  server 127.0.0.1:3000;
  keepalive 16;
}

server {
  listen 443 ssl http2;
  server_name example.com;

  # ssl_certificate / ssl_certificate_key lines go here

  client_max_body_size 2m;

  location / {
    proxy_pass http://app;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}

The proxy changes what your app sees. The TCP peer is now the proxy, not the user, so req.socket.remoteAddress is always the proxy's address. The real client address arrives in the X-Forwarded-For header, and the original protocol in X-Forwarded-Proto. Your code must read them, but only when the request really came from your own proxy, because any client can send those headers itself. A client that fakes X-Forwarded-For: 1.2.3.4 could otherwise bypass rate limits or poison your logs.

Node.js Reading the client address behind a proxy safely

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.

In the second request the client claims to be 1.2.3.4, but the app reads the last entry, which was added by the trusted proxy, and so reports 203.0.113.9 (a documentation-only address standing in for the real client). Frameworks have this built in; Express calls it trust proxy. Set it to the exact number of proxies you have, not to true.

Serverless

In a serverless platform you do not run a server. You export a handler function that receives an event and returns a response; the platform starts instances when requests arrive and may freeze or destroy them between requests. The model changes how you code:

  • Cold starts: the first request after idle time pays for starting the runtime and loading your code. Keep imports lean (this is one case where bundling and minifying pay off; see Building and Bundling).
  • No background work after you return a response; the instance may be frozen.
  • No local state you can rely on; any variable outside the handler lives only as long as that warm instance.
  • Connections to databases are a problem at high concurrency. Use connection pooling services or HTTP-based drivers.

The shape of a handler is just a function, so you can test it like any other:

Node.js A serverless-style handler

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.

Serverless suits spiky or low traffic and small APIs. It is a poor fit for long-lived connections (WebSockets), long computations or workloads that need predictable low latency, where a container is better.

Releasing without downtime

Downtime during a deploy is avoidable. The standard techniques all rely on running two versions side by side for a short time:

  • Rolling update: start new instances, wait until they report ready, then stop old ones one by one. Kubernetes and most platforms do this by default. It needs the health checks and graceful shutdown above.
  • Blue-green: run a complete new environment ("green"), test it, then switch the load balancer from the old ("blue") to the new. Rolling back is a switch back.
  • Canary: send a small share of traffic to the new version first and watch the error rate before going further.

Because versions overlap, your database migrations must be backward compatible: the old code must keep working against the new schema. The usual pattern is expand, migrate, contract: add the new column (old code ignores it), deploy code that writes both, backfill, deploy code that reads the new one, and only later drop the old column. Renaming a column in a single step is how deploys cause outages.

A pre-flight checklist

  • NODE_ENV=production, configuration from environment variables, no secrets in the image or repository.
  • Run as a non-root user; one process per container.
  • Start with node directly (not through npm start or a shell) so signals arrive.
  • SIGTERM handler that stops accepting connections and drains in-flight work, with a timeout.
  • /healthz and /readyz endpoints; readiness fails during shutdown.
  • Logs to stdout, structured, with request IDs.
  • Memory limit set in the platform and, if needed, --max-old-space-size slightly below it (see V8, Memory and Garbage Collection).
  • Reverse proxy or load balancer with TLS in front; correct handling of X-Forwarded-* headers.
  • Reproducible builds: npm ci, a lock file, a pinned Node.js major version (use an LTS line).
  • A tested way to roll back.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a Dockerfile start a Node.js app with CMD ["node", "server.js"] instead of CMD npm start?

    With npm (and a shell) in between, SIGTERM often does not reach your program, which then gets killed after the timeout instead of draining requests.
  2. 2. What is the purpose of copying package.json and running npm ci before copying the rest of the source in a Dockerfile?

    Layers are cached in order. Dependencies change rarely, so keeping them in an earlier layer avoids reinstalling on every code change.
  3. 3. What should a graceful shutdown handler do after receiving SIGTERM?

    The goal is not to cut off users mid-request. Stop taking new work, finish the current work, release resources, then exit, with a timeout as a safety net.
  4. 4. Behind a reverse proxy, why is it risky to trust the X-Forwarded-For header unconditionally?

    Only trust forwarding headers when the request comes from your own proxy, and read the entry that the proxy added.
  5. 5. Why must database migrations be backward compatible when you use rolling updates?

    During a rolling update both versions serve traffic against the same schema, so a change must work for both. Use expand, migrate, contract.

Summary

  • Make the app deployment-friendly first: environment-based config, stateless processes, logs on stdout, fast start, graceful stop.
  • Containers are the portable default: use multi-stage builds, npm ci, --omit=dev, a non-root user and the exec form of CMD.
  • On bare servers use systemd or PM2; inside containers run one Node process per container.
  • Handle SIGTERM: close the server, finish in-flight requests, release resources, and set a timeout.
  • Put a reverse proxy in front for TLS, static files and load balancing, and trust X-Forwarded-* headers only from that proxy.
  • Serverless trades control for convenience; watch cold starts and avoid background work after the response.
  • Release with rolling, blue-green or canary strategies, and keep migrations backward compatible.

Next: Real-Time, Queues and the Wider Ecosystem