hi@onela
_

Ubuntu环境安装配置Nodejs与pm2进程守护

May 30, 2024 · 3 min · Nodejs

Ubuntu 20.04 上安装 Node.js 和 npm

Node环境配置

推荐使用官方脚本安装,例如在ubuntu系统中使用nvm

shell

# Download and install nvm:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
# in lieu of restarting the shell
\. "$HOME/.nvm/nvm.sh"
# Download and install Node.js:
nvm install 22
# Verify the Node.js version:
node -v # Should print "v22.17.0".
nvm current # Should print "v22.17.0".
# Verify npm version:
npm -v # Should print "10.9.2".
 

pm2开机启动

root账户下启动pm2一般直接执行pm2 startup执行开机启动即可生效,但是针对非root账户大概率会失败。

shell

# 踩坑点,如果简单执行pm2 startup机器重启之后进程无法自动恢复,执行pm2 update可恢复,但是需要手动执行.
pm2 startup ubuntu -u myuser --hp /home/myuser/
 
# pm2 startup 创建开机启动脚本
# ubuntu 你服务器使用的平台.ubuntu用户改成ubuntu即可
# -u myuser 使用哪个用户启动
# --hp define home path when generating startup script.用户的家目录.也是放置刚才执行pm2 save 之后产生的dump.pm2 文件的路径
 
# ubuntu环境会生成一串环境环境变量设置代码,复制执行即可实现开机启动

pm2 进程守护,开机自动启动运行程序进程。

通过pm2启动程序,在机器重启之后默认没有自动加载,执行如下命令:

shell

# pm2启动进程之后系统重启会丢失,需要保存pm2程序启动列表
pm2 save
# [PM2] Saving current process list...
[PM2] Successfully saved in /home/test/.pm2/dump.pm2

pm2 更新到最新稳定版本

shell

# Install latest PM2 version
$ npm install pm2@latest -g
# Save process list, exit old PM2 & restore all processes
$ pm2 update

pm2-logrotate

shell

# 安装pm2日志分割(前提是已经安装pm2)
pm2 install pm2-logrotate
 
# 查看配置
pm2 conf pm2-logrotate
 
# 配置日志大小10M
pm2 set pm2-logrotate:max_size 10M
# 保存30个文件
pm2 set pm2-logrotate:retain 30
# 配置日志是否压缩
pm2 set pm2-logrotate:compress false
# 配置日志时间日期格式化显示
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss
 
pm2 set pm2-logrotate:workerInterval 30
 
pm2 set pm2-logrotate:rotateInterval 10 * * * *
 
pm2 set pm2-logrotate:rotateModule true
 

2.2.3 pm2日志清理

shell

# pm2日志清理
pm2 flush
 
# 清理pm2日志:清理2天以前的日志文件
find /root/.pm2/logs -mtime +2 -name "*.log"  -exec rm -rf {} \;
 
# 删除目录
find . -type d  -mtime +2 -name "*" -exec rm -rf {} \;
# 删除空目录
find . -type d -empty -delete
 
# 清除业务系统日志
find /usr/local/logs/auth -mtime +2 -name "*.log"  -exec rm -rf {} \;
find /usr/local/logs/auth -mtime +2 -name "*.html"  -exec rm -rf {} \;
find /usr/local/logs/gateway -mtime +2 -name "*.log"  -exec rm -rf {} \;
find /usr/local/logs/jobmanager  -mtime +2 -name "*.zip"  -exec rm -rf {} \;
find /usr/local/logs/statistic -mtime +2 -name "*.log"  -exec rm -rf {} \;
find /usr/local/logs/statistic -mtime +2 -name "*.html"  -exec rm -rf {} \;
find /usr/local/logs/system -mtime +2 -name "*.log"  -exec rm -rf {} \;
find /usr/local/logs/system -mtime +2 -name "*.html"  -exec rm -rf {} \;