PM2是一个流行的Node.js进程管理器,可以帮助您管理和监控Node.js应用程序。
可以使用PM2将应用程序设置为开机自动启动。
1、首先安装PM2:npm install -g pm2
npm install pm2@latest -g
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
added 157 packages in 14s
12 packages are looking for funding
run npm fund
for details
root@us:~# npm install -g pm2
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
added 162 packages in 29s
14 packages are looking for funding
run `npm fund` for details
npm notice
npm notice New patch version of npm available! 10.5.0 -> 10.5.2
npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.5.2
npm notice Run npm install -g npm@10.5.2 to update!
npm notice
root@us:~# npm install -g npm@10.5.2
changed 55 packages in 4s
25 packages are looking for funding
run `npm fund` for details
2、使用命令(pm2 examples)迅速看例子,启动应用程序并将其设置为开机自动启动:
# pm2 examples
[PM2] pm2 usage examples:
- Start and add a process to the pm2 process list:
$ pm2 start app.js --name app
- Show the process list:
$ pm2 ls
- Stop and delete a process from the pm2 process list:
$ pm2 delete app
- Stop, start and restart a process from the process list:
$ pm2 stop app
$ pm2 start app
$ pm2 restart app
- Clusterize an app to all CPU cores available:
$ pm2 start -i max
- Update pm2 :
$ npm install pm2 -g && pm2 update
- Install pm2 auto completion:
$ pm2 completion install
Check the full documentation on https://pm2.keymetrics.io/
root@moneyslow.com:# netstat -anlp|grep 3000
tcp6 0 0 :::3000 :::* LISTEN 20778/node /root
3、使用pm2 save命令保存当前的进程列表,以便在系统重启后自动恢复。
pm2 save
[PM2] Saving current process list…
[PM2] Successfully saved in /root/.pm2/dump.pm2
如果需要有变更时自动重启的话,可以加入 --watch 选项。
假设你加了好几个服务的话,可以使用 pm2 list 或 pm2 ls 来查看这个列表。
开机自动执行 pm2
由於这是在 server 上管理,為了避免我们不小心重开机,或是 server 异常断电重开后服务没有跟著开起来,我们应该确保 pm2 可以在开机时自动重开,并执行我们设定的这些服务。
首先执行 pm2 startup 指令,设定开机自动啟动 pm2。
如果提示 To setup the Startup Script, copy/paste the following command:,记得把那行指令复製贴上执行一次。
接著执行 pm2 save 指令,让 pm2 记得我们设定了这些服务,下次啟动 pm2 的时候要自动执行这些东西。
重启服务器试试。