PM2 的安装和使用

PM2 是一个进程守护管理器,它将帮助您管理和保持您的应用程序 24/7 在线

安装 PM2

由于 PM2 依赖 Node,这里我们需要先安装Node,或者访问 nodesource 查看最新版本并下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
apt update && apt install curl gnupg2 ca-certificates -y

## 指定node版本
NODE_MAJOR=21

## 添加 Node 存储库
mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list

## 安装 Node
apt update && apt install nodejs -y

## 检查安装
node -v
npm -v

安装 PM2

1
npm install pm2 -g

使用 PM2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
## 通过PM2启动程序并后台运行和进程守护
pm2 start app.js
pm2 start bashscript.sh
pm2 start python-app.py
pm2 start binary-file

## pm2 start ./二进制文件 -n 别名 -- 要传递的参数
pm2 start ./app -n name -- -config config.json

## 保存程序列表以便服务器重启后自动启动它们
pm2 save

## 服务器启动时自动启动pm2
pm2 startup

pm2 stop app # 停止程序
pm2 status app # 查看状态
pm2 restart app # 重启程序
pm2 show app # 查看程序的参数信息
pm2 log app # 查看程序日志
pm2 del app # 删除程序
pm2 ls # 查看已部署的程序列表
pm2 monit # 监控程序状态
pm2 flush # 清理所有日志文件
pm2 update # 更新 pm2 状态

PM2 模块

PM2 具有模块系统,你可以安装一些附加模块扩展 PM2,相当于 PM2 的插件。点击访问 PM2 模块存储库。
这里推荐一个日志管理插件 pm2-logrotate

1
2
3
4
5
## 安装
pm2 install pm2-logrotate

## 设置每周三0点1分清理日志
pm2 set pm2-logrotate:rotateInterval '1 0 * * 3'