Open In App

Explain Graceful shutdown in Express.js

Last Updated : 25 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

What is Graceful Shutdown?

When we work with express apps, we often use program managers like Forever, PM2, SystemD, etc. When the user wants to end the connection or stop the server, first all the connections and requests need to close or be completed before shutting down the app. This means no traffic or data should remain open and the resources of the app that were in use should be closed.  

Procedure of Graceful Shutdown: For this purpose, a SIGTERM (the program manager sends it ) signal is sent to the application that tells it that it is going to be killed. After getting this signal, the app stops accepting the new requests, by letting the load balancer know that is not going to accept any new requests. All the active requests are finished. All the data and the traffic that includes database connections are cleaned up. After all, this process occurs the app exits the process with an exit status of 0.

This is the whole procedure of a graceful shutdown. This avoids any side effects on conflicts that may occur on closing the server and the new deployment can be started without any kind of difficulty.

Let us understand with the help of an example.

Step 1: First, we need to catch the SIGTERM signal that we sent to the application. We  use the process.on( ) function  for this purpose.

function gracefulshutdown() {
    console.log("Shutting down");
    myApp.close(() => {
        console.log("HTTP server closed.");
        
        // When server has stopped accepting 
        // connections exit the process with
        // exit status 0        
        process.exit(0); 
    });
}

process.on("SIGTERM", gracefulshutdown);

Step 2: When the SIGTERM signal is caught,  we call the graceful shutdown function where we close the application successfully.

Example: In this, we start a basic express server. Your app will shutdown gracefully.

Javascript




const express = require("express");
const myApp = express();
const port = 3000;
  
// Starting the server
myApp.get("/", (req, res) => { 
    res.send("Your express app has started!"); 
});
  
// App listening on port 3000
myApp.listen(port, () => {
    console.log(`App running at http://localhost:${port}`);
});
  
  
function gracefulshutdown() {
    console.log("Shutting down");
    myApp.close(() => {
        console.log("HTTP server closed.");
          
        // When server has stopped accepting connections 
        // exit the process with exit status 0
        process.exit(0); 
    });
}
  
process.on("SIGTERM", gracefulshutdown);



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads