Graceful shutdown lets your Node.js app close smoothly. It finishes tasks and frees resources before stopping.
0
0
Graceful shutdown handling in Node.js
Introduction
When you want to stop your server without dropping active connections.
When your app needs to save data or cleanup before exiting.
When deploying updates and you want to avoid sudden crashes.
When handling system signals like Ctrl+C or termination requests.
When you want to close database connections or file streams safely.
Syntax
Node.js
process.on('SIGINT', () => { // cleanup code here server.close(() => { console.log('Server closed'); process.exit(0); }); });
process.on listens for system signals like SIGINT (Ctrl+C).
server.close() stops accepting new connections and waits for existing ones to finish.
Examples
Handles
SIGTERM signal, common in container or cloud environments.Node.js
process.on('SIGTERM', () => { console.log('SIGTERM received, shutting down'); server.close(() => process.exit(0)); });
Runs async cleanup before closing server on Ctrl+C.
Node.js
process.on('SIGINT', async () => { await cleanupDatabase(); server.close(() => process.exit(0)); });
Sample Program
This Node.js server listens on port 3000. When you press Ctrl+C, it logs a message, stops accepting new requests, and exits cleanly.
Node.js
import http from 'node:http'; const server = http.createServer((req, res) => { res.end('Hello, world!'); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); process.on('SIGINT', () => { console.log('\nSIGINT received: closing server'); server.close(() => { console.log('Server closed gracefully'); process.exit(0); }); });
OutputSuccess
Important Notes
Always close resources like database connections inside the shutdown handler.
If you don't call process.exit(), the app may hang waiting for tasks.
Test shutdown by pressing Ctrl+C in the terminal where your app runs.
Summary
Graceful shutdown helps your app stop safely without losing data.
Use process.on to listen for stop signals like SIGINT or SIGTERM.
Close servers and cleanup resources before exiting.