Ubuntu 上 Node.js 集群部署实战
一 环境准备与 Node.js 安装
二 方案一 内置 Cluster 模块实现多进程
const cluster = require(‘cluster’); const http = require(‘http’); const numCPUs = require(‘os’).cpus().length;
if (cluster.isPrimary) {
console.log(主进程 ${process.pid} 正在运行);
for (let i = 0; i < numCPUs; i++) cluster.fork();
cluster.on(‘exit’, (worker) => {
console.log(工作进程 ${worker.process.pid} 已退出,正在重启...);
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end(Hello from worker ${process.pid}\n);
}).listen(3000);
console.log(工作进程 ${process.pid} 已启动);
}
三 方案二 使用 PM2 一键集群与守护
四 多实例与反向代理及高可用
五 生产要点与常见问题