Load Balance 4 instances of api.js node js
Step 1: Install the necessary dependencies using the following command:
npm install http-proxy
Step 2: Create a new file named loadBalancer.js
and add the following code to it:
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const addresses = [
{ target: 'http://localhost:3001' },
{ target: 'http://localhost:3002' },
{ target: 'http://localhost:3003' },
{ target: 'http://localhost:3004' }
];
const selectTarget = () => {
const index = Math.floor(Math.random() * addresses.length);
return addresses[index];
};
http.createServer((req, res) => {
const target = selectTarget();
proxy.web(req, res, target);
}).listen(3000);
Step 3: Run the loadBalancer.js
file using the following command:
node loadBalancer.js