生产部署三件事:进程守护、多核利用、日志可查。PM2 一站解决,结尾附部署配置小案例。
一、为什么需要 PM2
裸 node app.js 的问题:
进程崩了就挂了、只用一个核、日志乱、重启靠人肉
PM2:进程守护 + 崩溃重启 + cluster 多核 + 日志管理 + 负载均衡
二、安装与常用命令
npm install -g pm2
pm2 start app.js # 启动
pm2 start app.js -i 4 # 4 个进程(cluster)
pm2 start app.js -i max # 按 CPU 核数
pm2 list # 进程列表
pm2 logs # 日志(实时)
pm2 restart app # 重启
pm2 reload app # 零停机重载(cluster)
pm2 stop app # 停止
pm2 delete app # 删除
pm2 monit # 监控面板
pm2 startup # 开机自启(生成 systemd)
pm2 save # 保存进程列表
三、ecosystem 配置文件
// ecosystem.config.js
module.exports = {
apps: [{
name: 'myapp',
script: 'app.js',
instances: 'max', // CPU 核数个进程
exec_mode: 'cluster',
max_memory_restart: '512M', // 内存超限自动重启
env_production: {
NODE_ENV: 'production',
PORT: 3000
}
}]
};
pm2 start ecosystem.config.js --env production
四、日志管理
pm2 logs myapp --lines 100 # 看最近 100 行
pm2 flush # 清空日志
# 日志分割(防单文件过大)
# ecosystem 配置:
# log_date_format: 'YYYY-MM-DD HH:mm:ss',
# out_file: '/var/log/myapp/out.log',
# error_file: '/var/log/myapp/err.log'
# 配合 logrotate 按天切割
五、零停机 reload
pm2 reload myapp # 逐个替换进程(用户无感知)
# cluster 模式才支持;单进程 fallback 为 restart
六、性能优化清单
□ cluster 多进程(-i max 吃满多核)
□ 内存监控(max_memory_restart 防泄漏)
□ Nginx 反代(静态/SSL 交给 Nginx)
□ 压缩(gzip/静态资源)
□ 缓存(Redis/HTTP 缓存头)
□ 数据库连接池(上限合理)
□ 慢请求日志(定位瓶颈)
七、小案例:生产部署配置
// ecosystem.config.js 完整版
module.exports = {
apps: [{
name: 'shop-api',
script: 'app.js',
instances: 2,
exec_mode: 'cluster',
max_memory_restart: '512M',
autorestart: true,
max_restarts: 10, // 1 分钟内最多重启 10 次
restart_delay: 5000, // 重启间隔
out_file: '/var/log/shop/out.log',
error_file: '/var/log/shop/err.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss',
merge_logs: true,
env_production: {
NODE_ENV: 'production',
PORT: 3000
}
}]
};
#!/bin/bash
# deploy.sh 发布脚本
git pull origin main
npm ci --production
pm2 reload shop-api --env production # 零停机更新
pm2 save # 持久化进程列表
curl -s http://127.0.0.1:3000/health || echo "健康检查失败"
ecosystem 全配置 + reload 零停机 + 发布脚本 + 健康检查 —— Node 生产部署的完整闭环。
八、总结
PM2 管进程(守护/cluster/reload);ecosystem.config.js 统一配置;max_memory_restart 防泄漏;日志分文件+logrotate;发布 = git pull + reload + 健康检查。