負載均衡可以把用戶的請求分攤到多個服務器上進行處理,從而實現了對海量用戶的訪問支持。負載均衡的架構如圖所示:
對于復雜的Web應用來說,用Nginx做前端負載均衡是理所當然的事。
下面,我們用Nginx做NodeJS應用的負載均衡。
1、配置Nginx
修改nginx.conf:
upstream sample {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
keepalive 64;
}
server {
listen 80;
....
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;
}
}
這里在3000端口和3001端口各有一個Node.js服務器,這兩個服務器在做同樣的工作。在upstream節,配置了兩個Node.js服務器。此外,我們還設置了proxy_pass http://sample做HTTP請求代理。
2、構建NodeJS服務器
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(200, {'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(200, {'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、訪問Nginx服務器
現在我們可以訪問http://127.0.0.1
可以看到如下的輸出:
Server running at http://127.0.0.1:3000/
Server running at 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: /favicon.ico-- port 3000