在 CentOS 上使用 Node.js 实现集群部署可以通过多种方式来完成,其中最常见的是使用 Node.js 内置的 cluster
模块。以下是一个基本的步骤指南:
首先,确保你已经在 CentOS 上安装了 Node.js。你可以使用以下命令来安装:
sudo yum install -y nodejs npm
或者使用 NodeSource 提供的安装脚本:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
创建一个简单的 Node.js 应用作为示例。假设你的应用文件名为 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/');
});
cluster
模块实现集群修改你的 app.js
文件,使用 Node.js 的 cluster
模块来创建多个工作进程:
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 app.js
虽然 cluster
模块可以实现基本的集群功能,但使用 PM2 可以更方便地管理 Node.js 应用。PM2 是一个进程管理器,可以让你轻松地启动、停止和监控 Node.js 应用。
首先,安装 PM2:
sudo npm install pm2 -g
然后,使用 PM2 启动你的应用:
pm2 start app.js -i max
-i max
参数会根据 CPU 核心数自动启动相应数量的工作进程。
你可以使用 PM2 提供的命令来监控和管理你的应用:
# 查看所有进程
pm2 list
# 查看某个进程的详细信息
pm2 show <app_name_or_id>
# 停止某个进程
pm2 stop <app_name_or_id>
# 重启某个进程
pm2 restart <app_name_or_id>
# 删除某个进程
pm2 delete <app_name_or_id>
通过以上步骤,你可以在 CentOS 上实现 Node.js 应用的集群部署,并使用 PM2 进行进程管理。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: centos下docker网络故障排查