温馨提示×

centos nodejs如何配集群

小樊
40
2026-09-05 23:41:27
栏目: 编程语言

CentOS 上配置 Node.js 集群,通常有两种常见方式:

  1. 使用 Node.js 自带的 cluster 模块(单机多核)
  2. 多台 CentOS 服务器 + 反向代理(Nginx / HAProxy)组成集群

下面分别说明。


一、单机多核集群(Node.js cluster 模块)

适合:一台 CentOS 服务器,多核 CPU

1. 示例 Node.js 代码

const cluster = require('cluster');
const http = require('http');
const os = require('os');

if (cluster.isMaster) {
  const numCPUs = os.cpus().length;
  console.log(`Master ${process.pid} is running`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker) => {
    console.log(`worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from Node.js cluster\n');
  }).listen(3000);

  console.log(`Worker ${process.pid} started`);
}

2. 启动

node app.js

3. 进程管理(推荐)

使用 pm2(生产环境强烈推荐):

npm install -g pm2
pm2 start app.js -i max
pm2 save
pm2 startup

二、多台 CentOS 服务器组成 Node.js 集群

适合:高可用、负载均衡

架构示例

Nginx (负载均衡)
 ├── Node1 (CentOS A:3000)
 ├── Node2 (CentOS B:3000)
 └── Node3 (CentOS C:3000)

1. 每台服务器部署 Node.js

# 安装 Node.js
curl -sL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs

2. 每台服务器运行 Node 服务

pm2 start app.js -i max

3. 在 CentOS 上安装 Nginx

yum install -y nginx

4. 配置 Nginx 反向代理

upstream node_cluster {
    server 192.168.1.10:3000;
    server 192.168.1.11:3000;
    server 192.168.1.12:3000;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://node_cluster;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

5. 启动 Nginx

systemctl start nginx
systemctl enable nginx

三、常见问题

1. 端口不通

firewall-cmd --add-port=3000/tcp --permanent
firewall-cmd --reload

2. Session 共享

  • 使用 Redis
yum install redis

3. 静态资源

  • 交给 Nginx 处理,不要走 Node

四、推荐方案总结

场景 方案
单服务器多核 Node cluster / pm2
多服务器 Nginx + Node + pm2
高可用 Nginx + Redis + 多节点

如果你愿意,我可以:

  • 给你一份 完整生产级 CentOS + Node + Nginx 配置
  • 或针对 Docker / Kubernetes 方案讲解

你现在是 单机还是多台服务器

0