在CentOS上配置Node.js的集群模式可以通过多种方式实现,以下是使用PM2(Process Manager 2)进行配置的步骤:
首先,确保你已经在CentOS上安装了Node.js。你可以使用NodeSource或者NVM(Node Version Manager)来安装。
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bash_profile
nvm install node
PM2是一个进程管理器,可以帮助你管理和监控Node.js应用程序。
sudo npm install pm2 -g
假设你已经有一个Node.js应用,如果没有,可以创建一个简单的示例应用。
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
PM2提供了多种方式来启动集群模式,以下是使用pm2 start
命令的示例。
pm2 start app.js -i max
-i max
参数告诉PM2根据CPU核心数启动相应数量的实例。
你可以使用以下命令查看集群的状态:
pm2 status
PM2还提供了监控界面,可以通过以下命令启动:
pm2 monit
你也可以通过配置文件来管理PM2进程。
创建一个名为ecosystem.config.js
的文件:
module.exports = {
apps: [{
name: 'my-app',
script: 'app.js',
instances: 'max', // or a number of instances
exec_mode: 'cluster',
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
}]
};
pm2 start ecosystem.config.js
pm2 logs
命令查看日志。autorestart: true
,PM2会在应用崩溃时自动重启实例。通过以上步骤,你可以在CentOS上成功配置Node.js的集群模式,并利用PM2进行管理和监控。