How to gracefully shu...
How to gracefully shu...
To gracefully shut down a Node.js server, you need to handle the appropriate system signals and ensure that all ongoing tasks are completed and resources are properly released before the server process exits. Here’s a step-by-step guide on how to implement a graceful shutdown in a Node.js application:
Node.js can listen for system signals like SIGINT
and SIGTERM
. These signals are used to indicate that the Node.js process should terminate. SIGINT
is typically sent when the user presses CTRL+C in the terminal, and SIGTERM
is sent by process managers like Kubernetes or Docker to gracefully stop a process.
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
Create a function called gracefulShutdown
that will handle the cleanup tasks necessary before shutting down the server. This function should close all active connections, save any final data needed, and perform any other cleanup tasks.
function gracefulShutdown() {
console.log('Received kill signal, shutting down gracefully.');
server.close(() => {
console.log('Closed out remaining connections.');
process.exit(0);
});
// Set a timeout to forcefully shut down after 10 seconds
setTimeout(() => {
console.error('Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 10000);
}
In the gracefulShutdown
function, use the server.close()
method to stop the server from accepting new connections. This method also waits for all existing connections to finish before the callback function is executed.
Ensure that your shutdown process ...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào