How to gracefully shutdown Node.js server?
How to gracefully shutdown Node.js server?
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.');
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.