使用nodejs pm2扩展服务器时端口的工作原理

时间:2016-08-07 04:21:51

标签: node.js server port scalability pm2

我正在学习如何在我设置的小沙箱中扩展服务器。这是非常简单的代码:

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const instanceId = parseInt(Math.random() * 1000);

//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "POST, GET");
  next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.get('/', function(req, res) {
  console.log(`[${new Date()}] ${req.method} ${req.originalUrl} from ${req.ip} at ${instanceId}`);
  res.send(`received at ${Date.now()} from ${instanceId}`);
});

app.listen(6069);

没什么好疯狂的,只是吐出日期和收到请求的实例。

用于扩展nodejs服务器的pm2文档建议我运行:

pm2 start server.js -i 5

完美无缺。当我使用npm模块loadtest对其进行压力测试时,这是一个示例输出:

server-0 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 847
server-1 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 261
server-3 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 328
server-2 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 163
server-4 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 351
server-0 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 847
server-3 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 328
server-1 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 261
server-2 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 163
server-4 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 351
server-0 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 847
server-3 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 328

这是我的问题。为什么没有节点抛出端口6069正在使用的错误?多个服务器正在尝试使用该端口 - 但没有抱怨。为什么?

1 个答案:

答案 0 :(得分:2)

PM2创建了它自己的“嵌入式负载均衡器,它使用循环算法来更好地在工作者之间分配负载”。因此,它基本上围绕您的应用程序包装负载均衡器,并将请求代理到它创建的每个节点。

  

使用循环调度策略时,master接受()all   传入连接并发送该特定的TCP句柄   与所选工人的联系(通过IPC)。