A Node.js graceful shutdown has four parts: catch SIGTERM, call server.close() so no new connections arrive, mark responses that are still running with Connection: close, and set a hard deadline that calls server.closeAllConnections() and exits. Skip the third step and a keep-alive client can hold your process open until the platform kills it.
Since Node 19, server.close() does most of its own cleanup. The part that caught us out was a request already running when the signal arrived.
What does Node do with SIGTERM by default?
With no listener, Node exits straight away. The process docs say SIGTERM and SIGINT have default handlers on non-Windows platforms that exit “with code 128 + signal number”, which is the 143 you see in container logs. Nothing drains. Any request mid-flight gets a reset socket.
Add a listener and that default goes away. The same docs are explicit: “If one of these signals has a listener installed, its default behavior will be removed.” We checked this on Node 26.13.0 with a handler that only logs. The process printed the message and carried on serving for as long as we let it. So a handler that forgets to close the server, or throws before it gets there, turns a clean stop into a wait for SIGKILL at the end of the platform’s grace period.
Windows is different again. SIGTERM “is not supported on Windows”, and sending one to a process there terminates it outright.
What does server.close() actually wait for?
server.close() stops the listener, so new connections are refused. Since v19.0.0 it also closes connections that are “not sending a request or waiting for a response”, which means idle keep-alive sockets go immediately. The callback fires once every remaining connection has gone.
We ran the same test server on Node 18.20.4, 24.12.0 and 26.13.0. A client made one request with a keep-alive agent and held the socket open, then we sent SIGTERM:
- On 24.12.0 and 26.13.0 the server closed within 2 ms of the signal.
- On 18.20.4 it sat there until our drain deadline cut it, because Node 18 waits for the idle socket’s keep-alive timeout. That timeout defaulted to 5000 ms on every version we tried.
If you still support Node 18, call server.closeIdleConnections() straight after server.close(). The docs say it does no harm on newer versions.
A new connection after close() got ECONNREFUSED on all three. That matters for load balancers, which we come back to below.
Why does an in-flight request keep the server open?
Say a request is halfway through when SIGTERM lands. server.close() correctly lets it finish. The response goes out with Connection: keep-alive, because that was decided when the request started, and the socket goes back to idle. close() already did its one sweep of idle sockets, so nothing reaps this one.
In our run a 3-second request finished at about 3.4 s, and then the process kept waiting until the 5-second deadline forced it. Without a deadline it would have waited for the keep-alive timeout to expire.
The fix is to change the response before it is sent. Track open responses, and on shutdown set Connection: close on any that have not written headers yet. Node then closes the socket after the response, and the close() callback fires as soon as the last one finishes. With that change, the same run exited at 3.4 s with code 0 on both 24.12.0 and 26.13.0.
A Node.js graceful shutdown handler you can copy
This is the server we tested. /slow stands in for a slow database call and /events for a long-lived stream; swap in your own routes.
import http from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
const port = Number(process.env.PORT ?? 3000);
const drainMs = Number(process.env.DRAIN_MS ?? 10_000);
let shuttingDown = false;
const inFlight = new Set();
const server = http.createServer(async (req, res) => {
inFlight.add(res);
res.on('close', () => inFlight.delete(res));
if (shuttingDown) res.setHeader('connection', 'close');
if (req.url === '/slow') {
await sleep(3000);
res.end('slow done\n');
return;
}
if (req.url === '/events') {
res.writeHead(200, { 'content-type': 'text/event-stream' });
const timer = setInterval(() => res.write('data: tick\n\n'), 1000);
res.on('close', () => clearInterval(timer));
return;
}
res.end('ok\n');
});
server.listen(port, () => console.log(`listening on ${port}, pid ${process.pid}`));
function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal} received, draining`);
// Responses still being worked on will close their socket when they finish,
// instead of going back to idle keep-alive.
for (const res of inFlight) {
if (!res.headersSent) res.setHeader('connection', 'close');
}
// Stop accepting connections. Idle keep-alive sockets close now (Node 19+);
// in-flight requests are allowed to finish.
server.close((err) => {
console.log('server closed');
if (err) process.exitCode = 1;
});
// Anything still open at the deadline gets cut, then we exit regardless.
setTimeout(() => {
console.log('drain deadline hit, closing remaining connections');
process.exitCode = 1;
server.closeAllConnections();
setTimeout(() => process.exit(1), 1000).unref();
}, drainMs).unref();
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
Three details are deliberate. Both timers are unref()’d, so a clean drain exits on its own without waiting for them. The shuttingDown guard stops a second Ctrl+C from running the sequence twice. And the deadline sets exit code 1, so your logs can tell a forced stop from a clean one.
Close database pools and flush telemetry inside the close() callback, not before it, or the requests you are draining lose their connections.
What about SSE streams and WebSockets?
A streaming response never finishes, so close() never calls back. Our /events stream held the process until the deadline every time, and closeAllConnections() ended it within a few milliseconds. That is the job the deadline does.
WebSockets need their own code. The docs say closeAllConnections() “does not destroy sockets upgraded to a different protocol, such as WebSocket or HTTP/2.” Close those through your WebSocket library, ideally with a close frame so clients reconnect elsewhere. Our comparison of SSE and WebSockets covers the reconnect side.
Why are requests still refused during a deploy?
Usually because the signal reached the process before the load balancer stopped sending traffic.
In Kubernetes the two happen side by side. The pod termination docs say the control plane evaluates removing the pod from EndpointSlices “at the same time as the kubelet is starting graceful shutdown”. Your process can close its listener while traffic is still on the way, and those requests get ECONNREFUSED.
The usual answer is a short preStop pause, so the endpoint change spreads before the signal arrives. The kubelet’s built-in sleep action (KEP-3960, stable in v1.34) needs no shell in the image:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: web
lifecycle:
preStop:
sleep:
seconds: 5
The hooks docs say the grace period “applies to the total time it takes for both the PreStop hook to execute and for the Container to stop normally”. With 30 seconds and a 5-second sleep, keep DRAIN_MS well under 25 seconds.
Is the signal reaching Node at all?
Check this first, because two common Dockerfile choices swallow it.
Shell-form CMD node server.mjs runs under /bin/sh -c, which the Dockerfile reference says “does not pass signals”. Use exec form, CMD ["node", "server.mjs"].
Then Node is PID 1, and the docker run docs note that PID 1 “ignores any signal with the default action”. With the handler above that is fine, since you are not relying on the default. Without one, run with --init (tini) or the container waits out its stop timeout.
Script runners are the other trap. npm forwards SIGTERM to the script, but node --run does not, as we found in our node —run vs npm run tests. In a container, start node directly.
What we would do
Put this handler in every long-running Node HTTP service, with the Connection: close step included. Set the deadline from the platform’s grace period, not from a guess, and add the preStop sleep on Kubernetes. On Cloudflare Workers there is no process to signal, so none of it applies; work that must outlive a response there, or on a serverless Next.js deploy, needs something like Next.js after() or a queue.
We build and run Node services for clients, including the deploy pipeline and the shutdown behaviour that keeps releases quiet. If yours drop requests on every deploy, our Node.js development work usually starts there.