一、安裝PM2
- nvm是官方安裝nodejs的工具,安裝方式如下:
# 安裝 nvm (Node 版本管理器)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
# 如果上面進度慢,可以嘗試國內鏡像版本
curl -o- https://gitee.com/mirrors/nvm/raw/v0.40.0/install.sh | bash
# 臨時生效
export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node
# 永久生效(寫入Shell配置文件)
echo 'export NVM_NODEJS_ORG_MIRROR="https://npmmirror.com/mirrors/node"' >> ~/.bashrc
source ~/.bashrc
# 下載并安裝 Node.js(可能需要重啟終端)
# 第一次安裝之后可能沒有 nvm 命令,退出終端,再進一遍就好了
nvm install 22
# 驗證環境中是否存在正確的 Node.js 版本
node -v # 應該打印 `v22.12.0`
# 驗證環境中是否存在正確的 npm 版本
npm -v # 應該打印 `10.9.0`
npm install pm2 -g
二、PM2的使用
pm2 -v
- 編寫pm2的js腳本,這里編寫(hexo啟動版本,hexo_run.js)
//run
const { exec } = require('child_process')
exec('hexo server',(error, stdout, stderr) => {
if(error){
console.log('exec error: ${error}')
return
}
console.log('stdout: ${stdout}');
console.log('stderr: ${stderr}');
})
#簡單啟動進程
pm2 start hexo_run.js
#啟動進程,命名為為hexo_run
pm2 start app.js --name hexo_run
#結束某個進程
pm2 stop ID/名字
#停止所有進程
pm2 stop all
#重新啟動所有進程
pm2 restart all
#重新加載一個由 PM2 管理的應用程序。重新啟動應用進程,不會中斷服務。
pm2 reload hexo_run.js
pm2 list
#查看所有進程狀態
pm2 logs
#查看某個進程狀態
pm2 logs ID/名字
#刪除某個進程
pm2 delete ID/名字
#刪除所有進程
pm2 delete all