Categories
JavaScript Answers

How to shut down a Node Express server gracefully when its process is killed?

Spread the love

To shut down a Node Express server gracefully when its process is killed, we use the '@moebius/http-graceful-shutdown package.

For instance, we write

const express = require("express");
const GracefulShutdownManager =
  require("@moebius/http-graceful-shutdown").GracefulShutdownManager;

const app = express();

const server = app.listen(8080);

const shutdownManager = new GracefulShutdownManager(server);

process.on("SIGTERM", () => {
  shutdownManager.terminate(() => {
    console.log("Server is gracefully terminated");
  });
});

to create a GracefulShutdownManager object.

Then we call shutdownManager.terminate to shut down the Express app gracefully. when the SIGINT signal is received, which is when the Express process is killed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *