Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 43 ยท Quality and Operations

Deployment and Production

Take an Express app to production: NODE_ENV, environment config, nginx as a reverse proxy, PM2, Docker, health checks, graceful shutdown and an Express 5 checklist.

An app that works on your laptop is not yet a service. In production it must start from a clean machine, read its settings from the environment, survive crashes, sit behind a proxy that speaks HTTPS, tell the platform whether it is healthy, and stop politely when it is replaced by a new version. None of this is magic, and most of it is a few dozen lines of configuration.

You cannot install Express or run servers like nginx on this site, so every real command, config file and Express call below is read-only. The two ideas that live inside your own code, health checks with graceful shutdown and fail-fast configuration, also run here on our small stand-in framework, which has the same (req, res, next) shape as Express.

A production checklist

Configure Read settings from the environment and fail fast.
Proxy Let nginx or a load balancer face the internet.
Supervise PM2, systemd or Docker restart crashes.
Report health Give the platform a URL to ask "are you OK?".
1 / 2

NODE_ENV and configuration

NODE_ENV=production is a convention that Express and many libraries read. Express itself, in production, caches compiled view templates, skips detailed error pages, and (together with libraries such as your logger) trims debug output. The variable is only a switch: it does nothing unless you set it, so put it in your service definition, not in your code.

Everything else that changes between your laptop and the server belongs in environment variables as well: the port, the database URL, secrets. This is the "config in the environment" rule from the twelve-factor approach, and it means the same build runs everywhere.

JavaScript
// config.js
const required = ['DATABASE_URL', 'SESSION_SECRET'];
const missing = required.filter((name) => !process.env[name]);
if (missing.length > 0) {
  throw new Error(`Missing environment variables: ${missing.join(', ')}`);
}

export const config = {
  env: process.env.NODE_ENV ?? 'development',
  port: Number(process.env.PORT ?? 3000),
  databaseUrl: process.env.DATABASE_URL,
  sessionSecret: process.env.SESSION_SECRET,
};

Crashing at startup because a variable is missing is a feature. A deploy that fails in two seconds is far better than one that boots and then fails on the first login. Newer Node versions can load a file with node --env-file=.env server.js; use that for development and let the real environment provide values in production. Never commit .env files with secrets (Project Setup and Structure shows the layout).

The first runnable example is a validated config loader plus an error handler that behaves differently in production. Both are things you would write in your own code.

Node.js Fail-fast config and a production-safe error 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.

The loader refuses to start without its variables. In development the error response includes the message, which helps you debug; in production the client only sees a generic text, because messages such as a database address are information you do not give to strangers. (The full message still belongs in your logs: see Logging and Debugging.)

Running behind a reverse proxy

Node can serve HTTP directly, but in production you normally put a reverse proxy in front: nginx, Caddy, a cloud load balancer. It terminates TLS (HTTPS), serves static files efficiently, buffers slow clients, and can spread traffic over several Node processes.

flowchart LR
  A["Browser"] -->|"HTTPS :443"| B["nginx<br/>TLS, static files"]
  B -->|"HTTP 127.0.0.1:3000"| C["Express process 1"]
  B -->|"HTTP 127.0.0.1:3001"| D["Express process 2"]

The proxy faces the internet; your processes listen only on a private address.

A minimal nginx server block (read-only):

NGINX
server {
  listen 443 ssl;
  server_name example.com;
  # ssl_certificate and ssl_certificate_key lines go here

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}

The proxy hides the real client, so Express would see every request coming from 127.0.0.1 over plain HTTP. The X-Forwarded-* headers carry the truth, but Express only believes them if you opt in:

JavaScript
app.set('trust proxy', 1); // trust exactly one proxy hop in front of the app

With that setting, req.ip, req.protocol and req.secure reflect the original client, and secure cookies and rate limiters work correctly. Use the number of proxies you really have: trusting everything lets any client forge its IP. See The Request Object and Security Best Practices.

Keeping the process alive

If an uncaught exception kills your process, something must start it again. You have three common choices.

PM2 is a Node-specific process manager. It restarts crashes, can run one worker per CPU core, and keeps logs:

JavaScript
// ecosystem.config.cjs
module.exports = {
  apps: [
    {
      name: 'api',
      script: './server.js',
      instances: 'max',
      exec_mode: 'cluster',
      env: { NODE_ENV: 'production', PORT: 3000 },
    },
  ],
};

Started with pm2 start ecosystem.config.cjs, it runs the app in cluster mode so several workers share one port. systemd (the Linux service manager) does the restarting without any extra tool, and Docker with a restart policy does it inside a container. Pick one supervisor; do not stack them.

Run at least two instances when you can, so one can restart while the other serves. This only works if your app keeps no important state in its own memory: sessions and caches then belong in a shared store such as Redis.

Docker

A container packages your app with its exact Node version. A typical Dockerfile:

DOCKERFILE
FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]

Four details matter. Copying package*.json first lets Docker cache the dependency layer, so code-only changes rebuild in seconds. npm ci --omit=dev installs exactly what the lockfile says and skips dev tools. USER node avoids running as root. And CMD ["node", "server.js"] in exec form makes Node the main process, so it actually receives the stop signal; running through npm start can swallow it. Add a .dockerignore listing node_modules and .env.

Health checks

Platforms need a cheap URL to ask your app how it is doing. Two questions are different:

  • Liveness ("should I restart you?"): the process is running and not stuck. Usually /healthz returns 200 with no dependencies.
  • Readiness ("send me traffic?"): the app can serve right now: it finished starting, and is not shutting down. /readyz may also check the database.

Keep liveness trivial. If it checks the database and the database blips, the platform will kill healthy processes and make things worse. Readiness may be stricter, because failing it only removes the instance from the pool.

Graceful shutdown

Deploys, scaling and restarts send your process SIGTERM. If you ignore it, the platform kills you a few seconds later with SIGKILL, and any request in progress is cut off. The graceful version:

  1. Mark the app as draining, so readiness returns 503 and the load balancer stops sending new requests.
  2. Call server.close(), which stops accepting connections but lets open requests finish.
  3. Close the database and other resources.
  4. Exit, with a timer as a safety net in case something hangs.
JavaScript
const server = app.listen(config.port);

function shutdown(signal) {
  console.log(`${signal} received, draining`);
  draining = true;
  server.close(async () => {
    await db.end();
    process.exit(0);
  });
  server.closeIdleConnections();
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

We cannot send a real SIGTERM in the browser, so the example calls the shutdown function directly. Watch the order of the lines: a slow request is already running when the shutdown starts.

Node.js Health checks and a graceful drain

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 that the slow request still completes after the shutdown began, readiness reports 503 meanwhile, and only then does the server finish closing. A production version also ends keep-alive connections and cancels long-lived ones such as streams.

Other production habits

  • Logs to stdout. Let the platform collect them; write structured JSON lines.
  • Do not serve static assets from Node when a proxy or CDN can (Static Files and Downloads).
  • Compress and cache at the edge where possible (Performance and Caching).
  • Run npm audit and keep dependencies updated; pin versions with a lockfile.
  • Set timeouts on server, database and outbound HTTP calls, so a slow dependency cannot hold every connection.
  • Handle unhandledRejection and uncaughtException by logging and exiting, and let the supervisor restart you into a clean state. Continuing after an unknown error risks corrupted state.

Never use the development error handler, a debugger port, or verbose stack traces on a public server. They leak file paths, queries and sometimes secrets.

Express 5 migration checklist

If you are upgrading an older app, these are the changes that most often break it (all read-only; run your test suite after each step):

  • Rejected promises are forwarded to your error handler. You can delete many try/catch ... next(err) wrappers in async handlers.
  • Path syntax changed (path-to-regexp 8): a bare * wildcard must be named, for example /files/*path; optional parts use braces such as /users{/:id}; regular expressions inside strings are no longer supported. See Route Parameters.
  • req.body is undefined until a body parser runs, and stays so when there is no body. Guard with req.body?.name.
  • Removed or renamed methods: res.json(status, obj) style signatures, res.send(status), req.param() and app.del() are gone; use res.status(...).json(...), req.params/req.query/req.body and app.delete().
  • req.query is a getter and no longer a mutable property; the default query parser is simple.
  • Node 18 or newer is required.

Upgrade on a branch, fix route patterns first, run the tests (Testing Express Apps), then deploy to a staging environment before production.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should an app crash at startup when a required environment variable is missing?

    Failing fast turns a hidden misconfiguration into an obvious deploy failure.
  2. 2. Express runs behind nginx and req.ip always shows 127.0.0.1. What fixes it?

    Express only trusts X-Forwarded-* headers when you enable trust proxy, and the number should match the proxies you really have.
  3. 3. During graceful shutdown, what should the server do when it gets SIGTERM?

    server.close() refuses new connections while letting current requests finish, so nobody gets a cut-off response.
  4. 4. Which health check should stay free of database calls?

    A liveness check that depends on the database could make the platform restart healthy processes during a database blip.
  5. 5. In Express 5, what happens when an async route handler throws or rejects?

    Express 5 handles rejected promises from handlers and middleware and passes the error to next().

Summary

  • Set NODE_ENV=production, read all settings from the environment and fail fast when something is missing.
  • Put nginx (or a load balancer) in front for TLS and static files, and set trust proxy to the real number of hops.
  • Use PM2, systemd or Docker to restart crashes, and run more than one instance with shared state outside memory.
  • Provide a trivial liveness URL and a stricter readiness URL.
  • Handle SIGTERM: drain, server.close(), clean up, exit, with a safety timer.
  • When migrating to Express 5, fix wildcard paths, req.body assumptions and removed methods first.

Next: Project: Todo REST API.