http-terminator
http-terminator copied to clipboard
Usage with Express and Cluster
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/
Any progress on this topic?
Contributors are always welcome.
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)
}
});
}