在 CentOS 上配置 Node.js 集群(Cluster),一般有 两种方式:
下面按常见场景说明。
curl -sL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs
node -v
// server.js
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isMaster) {
const cpus = os.cpus().length;
console.log(`Master ${process.pid} is running`);
for (let i = 0; i < cpus; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.end('Hello from worker ' + process.pid);
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}
node server.js
访问:
curl http://localhost:3000
✅ 利用多核 CPU,自动重启 worker
npm install -g pm2
pm2 start app.js -i max
-i max:根据 CPU 核心数自动启动
pm2 list
pm2 logs
pm2 restart all
pm2 stop all
pm2 delete all
pm2 startup
pm2 save
✅ 生产环境最常用方式
pm2 start app.js -i 4
yum install -y nginx
upstream node_cluster {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003;
}
server {
listen 80;
location / {
proxy_pass http://node_cluster;
}
}
systemctl restart nginx
| 场景 | 推荐方案 |
|---|---|
| 单机多核 | Node cluster / PM2 |
| 生产环境 | PM2 |
| 高并发 | Nginx + PM2 |
| 多服务器 | Nginx + 多台 CentOS |
如果你能说明:
我可以给你一套 可直接用的配置。