Every deploy, autoscale event and container restart sends your process a signal. If you ignore it, in-flight requests die and database work is cut off halfway. A proper Node.js graceful shutdown stops new traffic, lets running requests finish, closes your resources and exits before the platform kills you. This guide builds that handler for Express step by step.

Why graceful shutdown matters

When a platform wants to stop your app, it usually sends SIGTERM, waits a grace period, then sends SIGKILL, which cannot be caught. Docker waits 10 seconds by default; Kubernetes waits 30 seconds by default (terminationGracePeriodSeconds). Without a handler, Node exits immediately on SIGTERM, so a client in the middle of a payment request gets a reset connection.

What SIGTERM does to a Node.js process

Once you register a listener with process.on('SIGTERM', ...), Node no longer exits by default. That is both the power and the risk: if your handler never calls process.exit() or the event loop never empties, the process hangs until SIGKILL. Always pair the handler with a hard timeout. Also handle SIGINT so Ctrl+C in development exercises the same code path.

How server.close() behaves in modern Node.js

Per the Node.js HTTP documentation, server.close() stops accepting new connections and, since v19.0.0, also closes connections that are idle (not sending or waiting for a request). In-flight requests are allowed to finish, and the callback fires once everything is closed. Two related methods exist, both added in v18.2.0:

  • server.closeIdleConnections() closes only idle keep-alive sockets.
  • server.closeAllConnections() forcibly closes every connection, including active ones. It does not destroy upgraded sockets such as WebSocket. The docs recommend calling it after server.close() to avoid races with new connections.

So the pattern is: call close(), wait for a deadline, and only then use closeAllConnections() as a last resort.

A complete Node.js graceful shutdown handler for Express

import express from 'express';

const app = express();
let shuttingDown = false;

app.get('/healthz', (req, res) => res.status(200).send('ok'));
app.get('/readyz', (req, res) =>
  shuttingDown ? res.status(503).send('shutting down') : res.status(200).send('ready')
);

app.get('/slow', async (req, res) => {
  await new Promise((r) => setTimeout(r, 5000));
  res.send('done');
});

const server = app.listen(3000, () => console.log('listening on 3000'));

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

  const force = setTimeout(() => {
    console.error('Drain timed out, closing remaining connections');
    server.closeAllConnections();
    process.exit(1);
  }, 25_000);
  force.unref();

  server.close(async (err) => {
    if (err) console.error(err);
    try {
      await closeResources();
      clearTimeout(force);
      process.exit(err ? 1 : 0);
    } catch (e) {
      console.error(e);
      process.exit(1);
    }
  });
}

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

The shuttingDown guard makes the handler idempotent, since some platforms send the signal twice. The timer is unref()'d so it never keeps the process alive on its own, and its value (25 seconds) sits below a 30-second platform grace period.

Closing MongoDB and Redis in the right order

Close the HTTP server first, so no new work starts, then close dependencies. Closing the database before requests finish causes those requests to fail.

import mongoose from 'mongoose';
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function closeResources() {
  await mongoose.connection.close();
  await redis.quit();
}

redis.quit() sends the QUIT command and lets pending replies finish, which is gentler than a hard disconnect. If you use transactions, finish them before this step; see Mongoose Transactions: A Practical Guide. If you keep rate limiter state in Redis, the same shutdown covers it, as described in How to Add Rate Limiting to a Node.js API with Redis.

Failing readiness checks during shutdown

A load balancer needs a moment to notice the instance is leaving. Returning 503 from the readiness endpoint once shuttingDown is true tells it to stop routing new requests. Keep the liveness endpoint returning 200 during the drain, otherwise the orchestrator may restart the container mid-drain. On Kubernetes, endpoint removal propagates asynchronously, so requests can still arrive just after SIGTERM. A short preStop sleep of a few seconds is a common way to cover that gap, and you can also add a small setTimeout before calling server.close() if you cannot change the manifest.

Docker and Kubernetes pitfalls

  • Shell-form CMD: CMD node server.js runs through a shell that may not forward signals. Use the exec form CMD ["node", "server.js"].
  • npm as PID 1: npm start may not forward SIGTERM to Node. Run node directly.
  • Budget the grace period: your drain deadline plus any preStop delay must be smaller than terminationGracePeriodSeconds, or SIGKILL arrives first.
  • Long-lived connections: WebSockets and server-sent events are not drained by close(). Notify clients and close them yourself.

If you also use request-scoped context, nothing special is needed on shutdown, but see AsyncLocalStorage in Node.js for logging which requests were still in flight.

Testing the shutdown locally

Start the server, then in another terminal call the slow route and signal the process while it runs:

curl localhost:3000/slow &
sleep 1
kill -TERM $(pgrep -f server.js)

You should see the draining log immediately and the curl response done arrive about four seconds later, followed by a clean exit. Hit /readyz right after the signal to confirm it returns 503. Note that the listening socket closes right away, so a brand-new connection will be refused, which is the expected behavior.

Conclusion

A solid Node.js graceful shutdown comes down to a few steps: set a flag, fail readiness, call server.close(), close databases after requests finish, and enforce a deadline with closeAllConnections() as a fallback. Add the handler to your service template once and every deploy becomes safer. Next, wire the same flow into your container manifest and verify the grace period math.