javascript / intermediate
Snippet
Graceful Shutdown with Process Signals
Handling termination signals like SIGTERM allows your application to stop accepting new requests and close existing connections or database handles before the process exits.
snippet.js
1
2
3
4
5
6
7
8
9
10
const http = require('node:http');const server = http.createServer((req, res) => res.end('OK')).listen(3000);process.on('SIGTERM', () => {console.log('SIGTERM received. Closing server...');server.close(() => {console.log('Server closed. Exiting process.');process.exit(0);});});
nodejs
Breakdown
1
process.on('SIGTERM', ...)
Registers a listener for the termination signal often sent by container orchestrators like Docker or Kubernetes.
2
server.close(() => { ... })
Stops the server from accepting new connections and waits for existing ones to finish before executing the callback.