Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Usage with Express and Cluster #19

Open
bluepuma77 opened this issue Sep 23, 2020 · 3 comments
Open

Usage with Express and Cluster #19

bluepuma77 opened this issue Sep 23, 2020 · 3 comments
Labels
documentation Improvements or additions to documentation

Comments

@bluepuma77
Copy link

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/

@gajus gajus added the documentation Improvements or additions to documentation label Sep 24, 2020
@bluepuma77
Copy link
Author

Any progress on this topic?

@gajus
Copy link
Owner

gajus commented Nov 17, 2020

Contributors are always welcome.

@davidbarkercv
Copy link

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)
    } 
  });

}


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

3 participants