Skip to content

Instantly share code, notes, and snippets.

@Cadienvan
Last active February 20, 2023 06:28
Show Gist options
  • Save Cadienvan/118d6f5c14ee65a60d36e8e008c180fe to your computer and use it in GitHub Desktop.
Save Cadienvan/118d6f5c14ee65a60d36e8e008c180fe to your computer and use it in GitHub Desktop.
How to create a reverse proxy using clusters in Node.js
const cluster = require('cluster');
const http = require('http');
if (cluster.isMaster) {
for (let i = 0; i < 10; i++) {
cluster.fork();
}
let workers = Object.values(cluster.workers)
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
workers = workers.filter(w => w.id !== worker.id);
});
const proxy = http.createServer((req, res) => {
// Randomly send request to one of the workers
const worker = workers[Math.floor(Math.random() * workers.length)]
const options = {
hostname: 'localhost',
port: 3000 + worker.id,
path: req.url,
method: req.method,
headers: req.headers
};
const proxyReq = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, {
end: true
});
});
req.pipe(proxyReq, {
end: true
});
})
proxy.listen(3000);
}
if (!cluster.isMaster) {
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world from worker ' + cluster.worker.id);
}).listen(3000 + cluster.worker.id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment