用Nginx做NodeJS应用的负载均衡
对于复杂的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;
-
}
- }
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/‘);
- });
现在我们可以访问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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。