Create your proxy server and load-balancer using node.js
Sometimes you have a server and you want to send all incoming requests to another server or you have your application running on several servers and want to divide requests between them. In programming and DevOps we call this system a load balancer.
A load balancer is a middleware in front of our applications that can protect the application server from handling more requests.
To reach these goals I want to use proxy-servers and load-balancers with node.js.A main and popular package for this function is http-proxy package that can be installed with npm.
npm install --save http-proxy
I use express to create my simple web applications.
npm install --save express
Now we create 3 same simple web applications with different ports with one route.
const express = require('express');const app = express();app.listen(3001, () => {console.log('Application is running on port 3001')})app.get('/', (req, res) => {return res.send('Response from Application 1')})
And also create other 2 applications with port 3002,3003
After making our applications now we have to implement proxy-server
// Required packagesconst http = require('http');const proxy = require('http-proxy');// Create proxy serverconst proxyServer = proxy.createProxyServer()const targets = ['http://localhost:3001','http://localhost:3002','http://localhost:3003']http.createServer((req, res) => {
// Add any needed fields to proxyServer.web(req, res, { target: targets[(Math.floor(Math.random() * 3))] })}).listen(3000, () => {console.log('Proxy server is running in port 3000')})
In the below code, as you see we want to send each request to one of our web applications by chance and in this condition, each application’s chance to get a coming request is 33 percent.
And we can also use a proxy server to link requests to another target
const proxy = require('http-proxy');const target = 'http://google.com';proxy.createProxyServer({ target }).listen(3000, () => {console.log('Proxy server is running on port 3000')})
All requests coming to a proxy server running on port 3000 will go to the target server or target URL.
- For your applications in a production step, it is better to use Nginx proxy webserver to handle requests with a load balancer and it will handle request traffic in applications automatically.
In the end, I hope this article to be useful.