Categories
JavaScript Answers

How to shut down an Express server gracefully when its process is killed with Node.js?

Spread the love

Sometimes, we want to shut down an Express server gracefully when its process is killed with Node.js.

In this article, we’ll look at how to shut down an Express server gracefully when its process is killed with Node.js.

How to shut down an Express server gracefully when its process is killed with Node.js?

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

To install it, we run

npm i @moebius/http-graceful-shutdown

Then we use it by writing

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

const app = express();

const server = app.listen(8080);

const shutdownManager = new GracefulShutdownManager(server);

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

We create a GracefulShutdownManager instance by calling the constructor with our server and assign it to shutdownManager.

And then we call shutdownManager.terminate to shut down our server gracefully when the SIGTERM signal is received.

Conclusion

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

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 *