根据这个 answer :
You should run multiple Node servers on one box, 1 per core and split request traffic between them. This provides excellent CPU-affinity and will scale throughput nearly linearly with core count.
明白了,为了简单起见,假设我们的盒子有 2 个核心。
我需要一个完整的示例,一个 Hello World
应用程序在使用 NGINX 的两个 Node 服务器之间进行负载平衡。
这还应该包括任何 NGINX 配置。
最佳答案
应用程序.js
var http = require('http');
var port = parseInt(process.argv[2]);
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(port);
console.log('Server running at http://localhost:' + port + '/');
nginx 配置
upstream app {
server localhost:8001;
server localhost:8002;
}
server {
location / {
proxy_pass http://app;
}
}
启动您的应用
node app.js 8001
node app.js 8002
HttpUpstreamModule documentation
额外的阅读 Material
- cluster module - 仍然是实验性的,但你不需要 nginx
- forever module - 以防您的应用崩溃
- nginx and websockets - 如何在新的 nginx 版本中代理 websockets
关于node.js - 使用 NGINX 与多个 Node 服务器负载平衡请求流量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15007485/