Listen for SIGTERM and SIGINT, stop accepting new connections, let in-flight requests finish and close resources before exiting. Learn the pattern and the Docker gotchas.
The short answer
#Handle the SIGTERM and SIGINT signals. In the handler, call server.close() so no new connections are accepted, wait for open requests to finish, close database pools and other resources, then exit. Add a timeout so a stuck connection cannot block shutdown forever.
_23import http from 'node:http';_23_23const server = http.createServer(app);_23server.listen(3000);_23_23function shutdown(signal) {_23 console.log(`${signal} received, shutting down`);_23_23 server.close(async (error) => {_23 await db.end();_23 process.exit(error ? 1 : 0);_23 });_23 server.closeIdleConnections();_23_23 setTimeout(() => {_23 console.error('Forcing shutdown');_23 server.closeAllConnections();_23 process.exit(1);_23 }, 10_000).unref();_23}_23_23process.once('SIGTERM', shutdown);_23process.once('SIGINT', shutdown);
Why it happens
#When a platform stops your app, during a deploy, a scale-down or a restart, it sends SIGTERM first and gives the process time to finish. Docker, Kubernetes and most hosting platforms work this way. Pressing Ctrl+C in a terminal sends SIGINT.
If you do not handle the signal, Node.js exits straight away. Requests that were half way through get cut off, users see failed calls, and writes to the database or a queue may be left incomplete. If the process ignores the signal for too long, the platform sends SIGKILL, which cannot be caught, and the same thing happens anyway. Kubernetes, for example, waits 30 seconds by default.
How to fix it
#Stop accepting work, then finish what is in flight
server.close() stops the server listening and calls its callback once every connection has closed. Keep-alive connections can stay open while idle, so server.closeIdleConnections() closes those without touching active requests. server.closeAllConnections() is the hard stop for the timeout path.
The unref() on the timer means the timer alone will not keep the process alive if everything else closes first.
Close everything else that holds the process open
Database pools, Redis clients, message consumers and intervals all keep the event loop busy. Close them in the shutdown path, in the reverse order you opened them. If the process does not exit on its own after that, something is still open.
_10async function closeResources() {_10 clearInterval(metricsTimer);_10 await queueConsumer.stop();_10 await db.end();_10}
Fail health checks while draining
Behind a load balancer, mark the instance as unhealthy as soon as shutdown starts, so traffic moves elsewhere while you finish existing requests.
_10let shuttingDown = false;_10_10app.get('/healthz', (req, res) => {_10 res.status(shuttingDown ? 503 : 200).end();_10});
Make sure the signal reaches Node.js in Docker
Use the exec form of CMD so Node.js is the main process and receives signals directly. The shell form runs your command through /bin/sh, which does not pass SIGTERM on.
_10# In a Dockerfile_10CMD ["node", "server.js"]
Running through npm start adds another process in between, which can also get in the way. Starting the container with docker run --init, or using a small init such as tini, handles signals and zombie processes properly.
Common pitfalls
#- Calling
process.exit()at the top of the handler, which kills in-flight requests just as if you had no handler. - Registering with
process.onand receiving the signal twice, so shutdown runs twice.process.onceavoids that. - No timeout. One slow client or a leaked connection can hang the shutdown until the platform kills the process.
- Testing only with Ctrl+C. Send
SIGTERMwithkill -TERM <pid>to test the path your platform actually uses. - Expecting
SIGTERMhandling on Windows. Windows does not support it in the same way;SIGINTfrom Ctrl+C does work.
Related reading
#Was this resource helpful?