Load Balancing can allocate the user's request to multiple servers for processing, thus realizing the access support to the massive users. The load-balanced architecture is shown in the figure:
For complex web applications, it's a matter of course to use Nginx to do front-end load balancing.
Below, we use Nginx to do nodejs application load balancing.
1. Configure Nginx
Modify nginx.conf:
Upstream Sample {
server 127.0.0.1:3000;
Server 127.0.0.1:3001;
keepalive;
}
server {
listen;
....
server_name 127.0.0.1;
....
Location/{
proxy_redirect off;
Proxy_set_header x-real-ip $remote _addr;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
Proxy_set_header X-forwarded-proto $scheme;
Proxy_set_header Host $http _host;
Proxy_set_header x-nginx-proxy true;
Proxy_set_header Connection "";
Proxy_http_version 1.1;
Proxy_pass http://sample
}
}
There is a node.js server on port 3000 and port 3001, and the two servers are doing the same work. In the upstream section, two Node.js servers are configured. In addition, we have set up Proxy_pass http://sample to do HTTP request proxy.
2. Build Nodejs Server
var http = require (' http ');
var morgan = require (' Morgan ');
var server1 = Http.createserver (function (req, res) {
console.log ("Request for:" + Req.url + "--port 3000");
Res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Hello node.js\n ');
Listen (3000, "127.0.0.1");
var server2 = http.createserver (function (req, res) {
console.log ("Request for:" + Req.url + "--port 3001");
Res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Hello node.js\n ');
Listen (3001, "127.0.0.1");
Server1.once (' Listening ', function () {
console.log (' Server running at Http://127.0.0.1:3000/');
};
Server2.once (' Listening ', function () {
console.log (' Server running at http://127.0.0.1:3001/');
};
3, access to Nginx server
Now we can visit http://127.0.0.1
You can see the following output:
Server running at Http://127.0.0.1:3000/
server running in http://127.0.0.1:3001/
Request for:/--Port 3001
Request for:/favicon.ico--Port 3000
Request for:/favicon.ico--Port 3001
request for:/--Port 3000
request for:/favicon.ico--Port 3001
Request For:/favicon.ico--Port 3000
request for:/--Port 3001
request for:/favicon.ico--Port 3000
request for: /favicon.ico--Port 3001
request for:/--Port 3000
request for:/favicon.ico--Port 3001
request for:/FA vicon.ico--Port 3000