node.js - 使用 NGINX 与多个 Node 服务器负载平衡请求流量

标签 node.js nginx

根据这个 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

关于node.js - 使用 NGINX 与多个 Node 服务器负载平衡请求流量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15007485/

相关文章:

javascript - Google Plus 身份验证回调不起作用

node.js - Docker利用了几个基础镜像

django - 为什么 nginx 在对链接的 docker 容器执行 `uwsgi_pass` 时返回 502?

node.js - 如何在可读的http流上运行Sharp转换并写入文件

javascript - 忽略提取中的自签名 SSL 证书

node.js - google chrome 扩展中远程 Node 服务器上的 socket.io

javascript - 当我只需要构建时,为什么 yarn 会安装开发依赖项?

Nginx 更改日志文件的所有者和权限

laravel - 在本地网络上共享代客站点

django - 带有docker的Django和nginx组成-静态文件未加载