NodeJS PM2

验证:未记录
适用版本
未记录
验证范围
尚未登记验证记录。

本文缩写(英文全称与中文含义)
缩写 英文全称/名称 中文含义
API Application Programming Interface 应用程序编程接口
CPU Central Processing Unit 中央处理器
EC2 Elastic Compute Cloud AWS 云服务器服务
ECS Elastic Container Service AWS 容器编排服务
PM2 PM2 process manager Node.js 进程管理工具名称
PPID Parent Process Identifier 父进程标识符
VM Virtual Machine 虚拟机

1. Important Points#

PM2 是 Node.js process manager,常用于 VM / bare metal 上管理 Node.js 进程:启动、重启、reload、日志、开机自启动。

use for:
    VM / EC2 上跑 Node.js service
    process restart on crash
    zero-downtime reload for cluster mode
    log file management
    startup after reboot

do not use as:
    Kubernetes / ECS replacement
    full deployment system
    observability system
    secret manager

简单判断:

VM deployment:
    PM2 is useful

Docker / ECS / Kubernetes:
    usually prefer one Node process per container and let orchestrator restart it

production VM:
    use ecosystem.config.cjs, not long pm2 command in package.json

2. Install#

npm install -g pm2
pm2 -v

如果使用 nvm,注意 systemd startup 时 PATH 可能和当前 shell 不一样,必须确认开机后能找到正确的 node 和 pm2。

3. Basic Commands#

# start app
pm2 start dist/main.js --name order-api

# list processes
pm2 list

# show one process detail
pm2 describe order-api

# logs
pm2 logs order-api

# restart / reload / stop / delete
pm2 restart order-api
pm2 reload order-api
pm2 stop order-api
pm2 delete order-api

常用区别:

restart:
    stop then start
    may have short downtime

reload:
    graceful reload when possible
    most useful with cluster mode

delete:
    remove process from PM2 process list

4. Ecosystem File#

生产环境建议使用 ecosystem.config.cjs,把 name、script、env、logs、instances 写清楚。

// ecosystem.config.cjs
module.exports = {
  apps: [
    {
      name: "order-api",
      script: "dist/main.js",
      cwd: "/opt/order-api",
      exec_mode: "fork",
      instances: 1,
      watch: false,
      out_file: "/var/log/order-api/out.log",
      error_file: "/var/log/order-api/error.log",
      merge_logs: true,
      time: true,
      env: {
        NODE_ENV: "production",
        APP_ENV: "prod",
        LOG_LEVEL: "info"
      }
    }
  ]
};

启动:

pm2 start ecosystem.config.cjs --only order-api
pm2 reload ecosystem.config.cjs --only order-api --update-env
pm2 save

字段说明:

name: PM2 process name
script: app entry file
cwd: working directory
exec_mode: fork or cluster
instances: process count; cluster mode can use max
watch: production usually false
out_file / error_file: stdout / stderr log path
merge_logs: cluster mode 合并日志
env: environment variables

5. Fork vs Cluster#

PM2 多进程要求应用可安全并发、会话状态外置;容器日志优先 stdout/stderr,不能依赖容器内文件长期留存。

fork:
    one Node.js process
    simplest and safest default
    good for most API / worker services

cluster:
    multiple Node.js worker processes
    can use multiple CPU cores
    reload can reduce downtime
    app must be stateless or session must be externalized

Cluster 示例:

module.exports = {
  apps: [
    {
      name: "order-api",
      script: "dist/main.js",
      exec_mode: "cluster",
      instances: "max",
      watch: false
    }
  ]
};

6. Startup After Reboot#

PM2 process list 默认只存在于当前 PM2 daemon 状态里。要开机恢复,需要 startup + save。

# generate systemd startup command
pm2 startup systemd

# run the command printed by pm2 startup, usually with sudo
# then save current process list
pm2 save

# check generated systemd unit
systemctl status pm2-$(whoami)

理解:

pm2 startup:
    creates systemd unit for PM2 daemon

pm2 save:
    saves current PM2 process list to resurrect on boot

pm2 resurrect:
    manually restore saved process list

7. Logs#

pm2 logs order-api
pm2 logs order-api --lines 200
pm2 flush order-api

默认日志位置:

$HOME/.pm2/logs

生产建议显式配置日志路径,或者安装 PM2 logrotate:

pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 100M
pm2 set pm2-logrotate:retain 14
pm2 set pm2-logrotate:compress true

容器环境不要依赖 PM2 file logs,优先 stdout / stderr,让平台收集日志。

8. Troubleshooting#

# PM2 view
pm2 list
pm2 describe order-api
pm2 logs order-api --lines 200

# OS process view
pgrep -af order-api
ps -fp REPLACE_PID
pstree -aps REPLACE_PID
cat /proc/REPLACE_PID/cgroup

# startup service
systemctl status pm2-REPLACE_USER
journalctl -u pm2-REPLACE_USER -n 200

判断进程是不是 PM2 管理:

PM2 evidence:
    pm2 list contains app name
    pm2 describe shows pid / script / cwd / env
    pstree parent chain contains PM2 daemon

not enough:
    PPID=1 only means current parent is systemd/init
    it does not prove the app was started by PM2

9. Common Pitfalls#

forgot pm2 save:
    app runs now but disappears after reboot

wrong user:
    pm2 list is per user
    root PM2 and app user PM2 are different process lists

nvm path issue:
    systemd startup cannot find node or pm2 after reboot

watch in production:
    file changes or logs can trigger unexpected restarts

cluster without stateless design:
    in-memory session / local cache can behave incorrectly

container misuse:
    do not run PM2 just to restart inside Kubernetes/ECS; let orchestrator manage restart

10. References#

搜索文档

输入关键词,搜索所有文档。

↑ ↓ 选择 · Enter 打开 · Esc 关闭