http-terminator icon indicating copy to clipboard operation
http-terminator copied to clipboard

Usage with Express and Cluster

Open bluepuma77 opened this issue 5 years ago • 3 comments

It would be great to get an example of how to combine http-terminator with Node Cluster.

https://nodejs.org/api/cluster.html https://rowanmanning.com/posts/node-cluster-and-express/

bluepuma77 avatar Sep 23 '20 21:09 bluepuma77

Any progress on this topic?

bluepuma77 avatar Nov 17 '20 09:11 bluepuma77

Contributors are always welcome.

gajus avatar Nov 17 '20 12:11 gajus

Example below - Listen for SIGTERM on the primary process and then send a message to your worker processes which in turns calls httpTerminator.terminate();

const cluster = require("cluster");
const os = require("os");
const numCPUs = os.availableParallelism();

if (cluster.isPrimary) {
  logger.info(`Primary process is running. Will fork ${numCPUs} clusters.`);
  
  // Sends a message to the workers on SIGTERM / SIGINT
  const handleSignal = (signal) => {
    for (const worker of Object.values(cluster.workers)) {
      worker.send(signal);
    }
  };

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log('worker died. restarting...')
    cluster.fork();
  }); 

  // Main process will send termination message to workers
  process.on("SIGTERM", () => handleSignal('SIGTERM'));
  process.on("SIGINT", () => handleSignal('SIGINT'));
  
}
else{
  const express = require('express')
  const app = express()
  const { createHttpTerminator } = require("http-terminator")
  
  // Your code here
  // ....
 
  async function shutdown(signal) {
    // Your shutdown logic
    
    await httpTerminator.terminate();
    process.exit(0);
  }
  
  // Only is called when clustering is not in use
  process.on("SIGTERM", shutdown);
  process.on("SIGINT", shutdown); 

  // Applies to clustering only
  process.on('message', async (msg) => {
    if (msg === 'SIGTERM' || msg === 'SIGINT'  ) {
      await shutdown(msg)
    } 
  });

}


davidbarkercv avatar Aug 01 '23 12:08 davidbarkercv