在Linux上,Node.js应用通过cluster模块利用多核CPU创建多个工作进程共享端口,实现负载均衡。使用PM2进行进程管理,支持自动重启、日志等功能。生产环境需配置Nginx反向代理,将请求转发至Node.js集群,以提升安全性与性能。
想让Node.js应用在Linux上跑得更快、更稳?集群部署是个好办法,它能把多核CPU的性能真正榨干。下面就来一步步拆解这个过程,从零开始,把集群跑起来。

长期稳定更新的攒劲资源: >>>点此立即查看<<<
先把基础打好——确保系统里装上了Node.js。如果还没装,直接从官方源拉一份,或者用NodeSource的脚本一键搞定。
# 使用NodeSource安装Node.js
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
假设你已经有个现成的应用,或者先写个简单的练练手。下面这个就是最基础的HTTP服务,监听3000端口,返回一句“Hello World”。
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Node.js自带的cluster模块就是干这个的——它能创建多个工作进程,所有进程共享同一个端口,实现负载均衡。核心逻辑很简单:主进程负责fork出子进程,每个子进程都跑同样的HTTP服务。
// cluster-app.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello World\n');
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}
直接运行刚才那个文件,就能看到主进程和多个工作进程同时启动。
node cluster-app.js
手动管理进程总归不便,这时候PM2就该出场了。它不仅是进程守护,还能自动重启、日志管理,甚至帮你做负载均衡。
sudo npm install pm2 -g
用pm2 start启动,加个-i max参数,PM2会自动根据CPU核心数创建工作进程,省心又省力。
pm2 start cluster-app.js -i max
随时查看进程状态和实时日志,对排查问题非常有用。
pm2 status
pm2 logs
pm2 stop cluster-app
pm2 restart cluster-app
到了生产环境,通常还会在Node.js前面加一层Nginx,做反向袋里。这样既能提升安全性,又能利用Nginx的静态文件处理、缓存等能力。
sudo apt-get update
sudo apt-get install nginx
编辑Nginx的配置文件(一般位于/etc/nginx/sites-a vailable/default),把请求转发到Node.js的3000端口。
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo systemctl restart nginx
至此,你的Node.js集群应用已经通过Nginx对外提供服务了。整个流程走下来,从单进程到多进程,再到进程管理和反向袋里,一个生产级部署方案就成型了。
侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述