Node.js graceful shutdown is the difference between a deploy that nobody notices and one that throws a burst of 502 errors at real users. Every orchestrator stops a process the same way: it sends SIGTERM, waits a few seconds, then sends SIGKILL. A Node.js server that ignores the first signal is killed mid-request, its keep-alive connections are cut, and half-written database transactions are rolled back. This guide shows a dependency-free server that handles the signal correctly, drains connections, exposes separate liveness and readiness health checks, and the matching settings for Docker, Compose, systemd and Kubernetes.

Node.js graceful shutdown sequence: receive SIGTERM, fail readiness, drain in-flight requests and keep-alive connections, close database pools and exit before the kill timeout
A Node.js graceful shutdown: signal, readiness off, connection drain, cleanup and a clean exit before the kill timeout.

From my own work: On client VPS setups the pattern I see most is a Node app started through npm inside Docker, with no signal handler at all. Every deploy waits the full ten seconds, then the container is killed. Adding twenty lines of shutdown code and starting node directly made deploys both faster and error-free.

Why deploys drop requests without graceful shutdown

Three things go wrong when a process exits abruptly:

  • In-flight requests fail. A checkout or an upload that started half a second before the signal gets a reset connection.
  • Keep-alive sockets are cut. A reverse proxy such as Nginx reuses idle upstream connections. If the app closes one at the moment the proxy sends a new request on it, the proxy returns a 502.
  • Traffic still arrives. Load balancers and service meshes take a few seconds to notice that an instance is leaving. Until they do, new requests keep coming to a process that has stopped listening.

A graceful shutdown handles all three in order: stop advertising readiness, keep serving while routing catches up, stop accepting new connections, finish what is in flight, release resources and exit. Node.js emits SIGTERM and SIGINT as process events you can listen to; without a listener, the default action terminates the process immediately (Node.js: signal events).

A Node.js graceful shutdown example without dependencies

The server below runs on Node.js 24 LTS or newer and needs no packages. It has a liveness endpoint, a readiness endpoint, a slow route to test draining, and a shutdown function with a forced-exit timer:

// server.mjs - Node.js 24 LTS, no dependencies
import http from "node:http";
import { setTimeout as sleep } from "node:timers/promises";

const PORT = Number(process.env.PORT ?? 3000);
const SHUTDOWN_DELAY_MS = Number(process.env.SHUTDOWN_DELAY_MS ?? 5000);  // let load balancers notice
const SHUTDOWN_TIMEOUT_MS = Number(process.env.SHUTDOWN_TIMEOUT_MS ?? 20000);

let shuttingDown = false;

// Stand-ins for real dependencies (database pool, Redis, queue consumer)
const db = {
  async ping() { return true; },
  async end() { console.log("db pool closed"); },
};

const server = http.createServer(async (req, res) => {
  if (req.url === "/livez") {
    // Liveness: the process can serve requests. No dependency checks here.
    res.writeHead(200, { "content-type": "text/plain" }).end("ok");
    return;
  }
  if (req.url === "/readyz") {
    // Readiness: should this instance receive traffic right now?
    const ok = !shuttingDown && (await db.ping().catch(() => false));
    res.writeHead(ok ? 200 : 503, { "content-type": "application/json", "cache-control": "no-store" })
       .end(JSON.stringify({ status: ok ? "ready" : "not-ready", shuttingDown }));
    return;
  }
  if (req.url === "/slow") await sleep(3000);  // simulates a long request
  if (shuttingDown) res.setHeader("connection", "close");
  res.writeHead(200, { "content-type": "text/plain" }).end("hellon");
});

server.keepAliveTimeout = 65_000;  // longer than the proxy's idle timeout
server.headersTimeout = 66_000;

server.listen(PORT, () => console.log(`listening on ${PORT}, pid ${process.pid}`));

async function shutdown(signal) {
  if (shuttingDown) return;
  shuttingDown = true;
  console.log(`${signal} received, failing readiness`);

  const force = setTimeout(() => {
    console.error("shutdown timed out, forcing exit");
    server.closeAllConnections();
    process.exit(1);
  }, SHUTDOWN_TIMEOUT_MS);
  force.unref();

  await sleep(SHUTDOWN_DELAY_MS);           // keep serving while traffic drains away
  server.close(async (err) => {             // stop accepting; wait for in-flight requests
    if (err) console.error("server.close error", err);
    await db.end();
    console.log("clean exit");
    process.exit(err ? 1 : 0);
  });
  server.closeIdleConnections();            // drop idle keep-alive sockets now
}

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

Test it locally. Start the server, begin a slow request, send SIGTERM while it runs, and check that the request still completes and readiness flips to 503:

SHUTDOWN_DELAY_MS=1000 node server.mjs &
PID=$!
curl -s localhost:3000/readyz            # {"status":"ready","shuttingDown":false}
curl -s localhost:3000/slow &            # takes 3 seconds
sleep 0.3 && kill -TERM $PID
curl -s localhost:3000/readyz            # {"status":"not-ready","shuttingDown":true}
wait                                     # the slow request prints "hello"
# server log: SIGTERM received ... db pool closed ... clean exit

Draining connections: close(), closeIdleConnections() and keep-alive

server.close() stops the server from accepting new connections and calls its callback once every existing connection has ended. Since Node.js 19 it also closes connections that are idle, and the explicit closeIdleConnections() call makes that behaviour obvious to readers. closeAllConnections() is the hammer: it destroys sockets even if a request is still running, so it belongs only in the forced-exit path (Node.js: server.close()).

Sending Connection: close on responses during shutdown tells clients and proxies not to reuse that socket, so busy keep-alive connections end after their current response instead of holding server.close() open.

The two timeout settings prevent a different, permanent source of 502s. Node’s default keepAliveTimeout is 5 seconds. If a proxy or load balancer keeps idle upstream connections open longer than that, Node may close a socket at the same moment the proxy reuses it. Set Node’s keep-alive timeout above the proxy’s idle timeout, and headersTimeout slightly above that. With Nginx, also enable upstream keep-alive explicitly:

upstream node_app {
    server 127.0.0.1:3000;
    keepalive 32;
    keepalive_timeout 60s;     # shorter than Node's keepAliveTimeout (65s)
}

server {
    location / {
        proxy_pass http://node_app;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_next_upstream error timeout http_502;
    }
}

The full proxy setup, with TLS and WebSocket headers, is in Nginx reverse proxy for Docker and Node apps.

Liveness vs readiness health checks

A single /health endpoint that checks the database is a common mistake. If the database has a short outage, every instance reports unhealthy, the orchestrator restarts all of them, and the restart storm makes recovery slower. Kubernetes separates the questions into three probe types (Kubernetes: configure probes), and the same split is useful anywhere:

Check Question it answers What to test On failure
Liveness (/livez) Is the process stuck beyond repair? Only that the event loop answers; no external dependencies Restart the process
Readiness (/readyz) Should this instance get traffic now? Shutdown flag, warm-up finished, critical dependencies reachable Remove from load balancing; no restart
Startup Has a slow-starting app finished booting? Same endpoint as liveness, with a longer budget Delay liveness checks until it passes

Keep both endpoints cheap, unauthenticated only on an internal port or path that the public proxy does not expose, and return Cache-Control: no-store so no cache ever answers for them.

Docker: PID 1, exec form, HEALTHCHECK and stop timeouts

docker stop sends SIGTERM (or the image’s STOPSIGNAL) to the container’s main process, waits 10 seconds by default, then sends SIGKILL (Docker: docker container stop). Two details decide whether your handler ever runs:

  • Use the exec form. CMD node server.mjs in shell form runs /bin/sh -c as PID 1, and the shell does not forward the signal. CMD ["node", "server.mjs"] makes Node itself PID 1.
  • Avoid npm as the entry point. npm start adds a parent process between Docker and your app; start node directly in production.
  • PID 1 has no default signal actions. The kernel does not apply default termination to PID 1, so a Node process without a handler ignores SIGTERM and waits for the kill. Your handler fixes that; docker run --init or init: true in Compose adds a tiny init that also reaps zombie child processes.
# Dockerfile
FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
EXPOSE 3000
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=15s --timeout=3s --start-period=20s --retries=3 
  CMD ["node", "-e", "fetch('http://127.0.0.1:3000/livez').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
CMD ["node", "server.mjs"]

Slim Node images do not ship curl, so the health check uses Node’s built-in fetch. The HEALTHCHECK options and their defaults are documented in the Dockerfile reference (Docker: HEALTHCHECK). Docker uses the result for its health status, and Compose can wait for it before starting dependent services. Give the container more time than your shutdown timeout:

# compose.yaml
services:
  app:
    build: .
    init: true
    stop_grace_period: 30s        # must exceed SHUTDOWN_TIMEOUT_MS (20s)
    environment:
      SHUTDOWN_DELAY_MS: "3000"
    restart: unless-stopped
  worker:
    build: .
    command: ["node", "worker.mjs"]
    depends_on:
      app:
        condition: service_healthy

The rest of a production Compose file, including limits and log rotation, is covered in the Docker Compose production checklist.

systemd: KillSignal and TimeoutStopSec

Without containers, systemd plays the same role. By default it sends SIGTERM to the service’s processes, waits TimeoutStopSec (90 seconds unless your distribution changes the default), then sends SIGKILL (systemd.kill manual). Make the wait explicit and slightly longer than your app’s own timeout:

# /etc/systemd/system/node-app.service
[Unit]
Description=Node.js app
After=network-online.target
Wants=network-online.target

[Service]
User=nodeapp
WorkingDirectory=/srv/node-app
Environment=NODE_ENV=production PORT=3000 SHUTDOWN_TIMEOUT_MS=20000
ExecStart=/usr/bin/node server.mjs
KillSignal=SIGTERM
KillMode=mixed
TimeoutStopSec=30s
Restart=on-failure

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl restart node-app
journalctl -u node-app -n 20 --no-pager     # look for "clean exit" 

KillMode=mixed sends the first SIGTERM only to the main process, so your handler controls child processes, and the final SIGKILL to the whole group. For extra isolation, combine this unit with the sandboxing options in systemd service hardening.

Kubernetes: probes, preStop and the grace period

When Kubernetes deletes a pod, removing it from Service endpoints and sending SIGTERM happen in parallel, so new requests can still arrive for a short time after the signal. The pod then has terminationGracePeriodSeconds, 30 by default, before it is killed (Kubernetes: pod termination). The shutdown delay in the server covers the routing gap; the probes and grace period complete the picture:

spec:
  terminationGracePeriodSeconds: 40
  containers:
    - name: app
      image: registry.example.com/node-app:1.8.2
      ports:
        - containerPort: 3000
      env:
        - name: SHUTDOWN_DELAY_MS
          value: "5000"
        - name: SHUTDOWN_TIMEOUT_MS
          value: "30000"
      startupProbe:
        httpGet: { path: /livez, port: 3000 }
        periodSeconds: 2
        failureThreshold: 30
      livenessProbe:
        httpGet: { path: /livez, port: 3000 }
        periodSeconds: 10
        failureThreshold: 3
      readinessProbe:
        httpGet: { path: /readyz, port: 3000 }
        periodSeconds: 5
        failureThreshold: 1

Some teams put the delay in a preStop hook instead of the app. Either works; do not do both, because the preStop time counts against the same grace period.

Closing databases, queues and timers

  • Database pools: call pool.end() for pg or mysql2, prisma.$disconnect() for Prisma, after server.close() finishes, so in-flight requests can still query.
  • Queue workers: stop taking new jobs first (for BullMQ, await worker.close() waits for active jobs), then close Redis connections.
  • Intervals and cron jobs: clear them, or unref() them so they never keep the process alive.
  • Cluster mode or PM2: each worker needs the same handler; the primary forwards the signal. Rolling restarts across workers are covered in “+L(‘high-concurrency-nodejs-clustering-zero-downtime-vps-2026′,’Node.js clustering and zero-downtime worker restarts’)+”.

Watch the readiness endpoint from outside too: an external monitor such as the one in the Uptime Kuma guide shows whether deploys produce any failed checks.

Node.js graceful shutdown checklist

  • SIGTERM and SIGINT handlers that run shutdown once.
  • Readiness fails immediately; a short delay lets routing catch up.
  • server.close(), idle connections closed, Connection: close during shutdown.
  • A forced-exit timer below the orchestrator’s kill timeout.
  • Database pools and queue consumers closed after requests finish.
  • Separate /livez and /readyz; liveness has no dependency checks.
  • Exec-form CMD, no npm wrapper, init: true, stop_grace_period, TimeoutStopSec or terminationGracePeriodSeconds above the app timeout.
  • Node keepAliveTimeout longer than the proxy’s idle timeout.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What is graceful shutdown in Node.js?

It is handling the SIGTERM signal so the server stops accepting new connections, finishes requests already in progress, closes database and queue connections and then exits on its own, instead of being killed in the middle of work.

Why does my Node.js container take 10 seconds to stop?

Docker sends SIGTERM and waits 10 seconds before SIGKILL. If Node runs as PID 1 without a SIGTERM handler, or a shell or npm wrapper does not forward the signal, nothing reacts and Docker waits the full timeout. Use the exec form of CMD and add a handler.

What is the difference between liveness and readiness checks?

Liveness asks whether the process is broken and should be restarted, so it should not depend on external services. Readiness asks whether the instance should receive traffic right now; it fails during startup, shutdown or when a critical dependency is unavailable, without causing a restart.

Does server.close() close keep-alive connections?

Since Node.js 19, server.close() also closes idle connections, and closeIdleConnections() does so explicitly. Connections with a request in progress stay open until the response finishes; closeAllConnections() destroys them and should only be used as a last resort.

How long should the shutdown timeout be?

Long enough for your slowest normal request plus the routing delay, and shorter than the kill timeout of the platform. A common setup is a 3 to 5 second delay, a 20 to 30 second app timeout and a platform grace period a few seconds longer.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.