Graceful shutdown lets your server close smoothly without dropping requests or losing data.
0
0
Graceful shutdown handling in Express
Introduction
When you want to update your server without breaking active connections.
When you need to stop your server safely during maintenance.
When you want to avoid errors from abruptly stopping the server.
When your app uses resources like database connections that need closing.
When you want to handle signals like Ctrl+C or system shutdown properly.
Syntax
Express
const express = require('express'); const app = express(); const port = 3000; const server = app.listen(port, () => { console.log(`Server running on port ${port}`); }); process.on('SIGINT', () => { console.log('Received SIGINT. Shutting down gracefully...'); server.close(() => { console.log('Closed out remaining connections.'); process.exit(0); }); // Optional: force exit after timeout setTimeout(() => { console.error('Could not close connections in time, forcefully shutting down'); process.exit(1); }, 10000); });
server.close() stops new connections but lets existing ones finish.
Listening to SIGINT lets you catch Ctrl+C to shut down nicely.
Examples
This listens for the SIGTERM signal, common in container shutdowns, to close the server gracefully.
Express
process.on('SIGTERM', () => { console.log('SIGTERM received, closing server'); server.close(() => { console.log('Server closed'); process.exit(0); }); });
Call
server.close() to stop accepting new requests but finish current ones.Express
server.close(() => {
console.log('Server stopped accepting new connections');
});Sample Program
This Express server listens on port 3000 and responds with 'Hello, world!'. When you press Ctrl+C, it catches the signal, stops accepting new requests, waits for current ones to finish, then exits cleanly.
Express
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello, world!'); }); const server = app.listen(port, () => { console.log(`Server running on port ${port}`); }); process.on('SIGINT', () => { console.log('Received SIGINT. Shutting down gracefully...'); server.close(() => { console.log('Closed out remaining connections.'); process.exit(0); }); setTimeout(() => { console.error('Could not close connections in time, forcefully shutting down'); process.exit(1); }, 10000); });
OutputSuccess
Important Notes
Always handle shutdown signals to avoid data loss or broken connections.
Use a timeout to force shutdown if connections hang too long.
Test shutdown by running the server and pressing Ctrl+C in the terminal.
Summary
Graceful shutdown helps your server stop safely without dropping requests.
Listen for signals like SIGINT or SIGTERM to trigger shutdown.
Use server.close() to finish current requests before exiting.