pm2 7.0.4 常用 CLI 命令与工具详解

pm2 7.0.4 常用 CLI 命令与工具详解:start/list/show/reload/stop/delete/scale、日志与监控、jlist 脚本化输出、全局参数速查与开机自启命令,全部命令与回显已在 Ubuntu 22.04 实测通过

pm2pm2进程管理2026/10/18

pm2 7.0.4 常用 CLI 命令与工具详解

目标:按「进程管理 → 日志与监控 → 脚本化输出 → 持久化与自启」的顺序逐一讲解 pm2 7.0.4 的常用 CLI 命令,每条命令给出参数说明与真实实测回显,读者可逐条照做复现。本文命令均在 Ubuntu 22.04 实测通过(pm2 7.0.4 / Node.js v22.23.3),安装步骤见《Ubuntu 22.04 安装 pm2 7.0.4 指南》,配置文件级参数见《pm2 7.0.4 配置参数详解》。

一、环境信息

  • 操作系统:Ubuntu 22.04(amd64),root 用户操作
  • pm2:7.0.4(pm2 --version 实测输出 7.0.4)
  • Node.js:v22.23.3(node -v 实测输出 v22.23.3)
  • npm:10.9.9
  • pm2 数据目录:/root/.pm2(守护进程日志 pm2.log、应用日志 logs/、恢复清单 dump.pm2)
  • 示例应用:/opt/demoapp/app.js,Node.js 内置 http 模块编写的最小 HTTP 服务,默认监听 3000 端口,返回一行含进程 PID 的文本:
const http = require("http");

const port = process.env.PORT || 3000;

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
  res.end("Hello from pm2 demo app, PID=" + process.pid + "\n");
});

server.listen(port, () => {
  console.log("demo app listening on port " + port + ", PID=" + process.pid);
});

应用返回文本中携带 PID=<进程号>,便于用 curl 直接验证请求落到了哪个实例——本文大量验证步骤依赖这一点。

二、工具概览

pm2 命令行由「1 个主命令 + 子命令 + 全局参数」构成。pm2 --help 输出全部参数与子命令清单(实测全量约 170 行,此处按功能域归类整理,参数行原文照抄):

pm2 --help

实测回显(按功能域归类节选,参数行为原文):

  Usage: pm2 [cmd] app

  Options:

    -V, --version                                                output the version number
    -s --silent                                                  hide all messages
    -n --name <name>                                             set a name for the process in the process list
    -i --instances <number>                                      launch [number] instances (for networked app)(load balanced)
    -o --output <path>                                           specify log file for stdout
    -e --error <path>                                            specify log file for stderr
    -l --log [path]                                              specify log file which gathers both stdout and stderr
    --log-date-format <date format>                              add custom prefix timestamp to logs
    --time                                                       enable time logging
    --env <environment_name>                                     specify which set of environment variables from ecosystem file must be injected
    -a --update-env                                              force an update of the environment with restart/reload (-a <=> apply)
    --max-memory-restart <memory>                                Restart the app if an amount of memory is exceeded (in bytes)
    --restart-delay <delay>                                      specify a delay between restarts (in milliseconds)
    --max-restarts [count]                                       only restart the script COUNT times
    -c --cron <cron_pattern>                                     restart a running process based on a cron pattern
    --watch [paths]                                              watch application folder for changes (default: )
    --merge-logs                                                 merge logs from different instances but keep error and out separated
    --no-autorestart                                             start an app without automatic restart
    -h, --help                                                   output usage information

  Commands:

    start [options] [name|namespace|file|ecosystem|id...]        start and daemonize an app
    stop [options] <id|name|namespace|all|json|stdin...>         stop a process
    restart [options] <id|name|namespace|all|json|stdin...>      restart a process
    reload <id|name|namespace|all>                               reload processes (note that its for app using HTTP/HTTPS)
    scale <app_name> <number>                                    scale up/down a process in cluster mode depending on total_number param
    delete|del <name|id|namespace|script|all|json|stdin...>      stop and delete a process from pm2 process list
    list|ls                                                      list all processes
    status                                                       (alias) list all processes
    jlist                                                        list all processes in JSON format
    prettylist                                                   print json in a prettified JSON
    monit                                                        launch termcaps monitoring
    dashboard|dash                                               launch dashboard with monitoring and logs
    flush [api]                                                  flush logs
    logs [options] [id|name|namespace]                           stream logs file. Default stream all logs
    describe <name|id>                                           describe all parameters of a process
    show <name|id>                                               (alias) describe all parameters of a process
    env <id>                                                     list all environment variables of a process id
    pid [app_name]                                               return pid of [app_name] or all
    id <name>                                                    get process id by name
    dump|save [options]                                          dump all processes for resurrecting them later
    resurrect                                                    resurrect previously dumped processes
    startup [platform]                                           enable the pm2 startup hook
    unstartup [platform]                                         disable the pm2 startup hook
    kill                                                         kill daemon
    ping                                                         ping pm2 daemon - if not up it will launch it
    update                                                       (alias) update in-memory PM2 with local PM2
    slist|sysinfos [options]                                     list system infos in JSON
    ecosystem|init [mode]                                        generate a process conf file. (mode = null or simple)
    reset <name|id|all>                                          reset counters for process

命令全景按功能域分为四类:进程管理(start/stop/restart/reload/delete/scale)、状态查询(list/status/show/describe/pid/id/jlist)、日志监控(logs/flush/monit/dashboard/slist)、持久化自启(save/resurrect/startup/unstartup/kill/update)。下文逐域详解。

三、前置条件

  • 已按《Ubuntu 22.04 安装 pm2 7.0.4 指南》完成 pm2 7.0.4 安装并验证 pm2 --version 输出 7.0.4;
  • 已准备第一节所示示例应用 /opt/demoapp/app.js;
  • 所有命令以 root 在任意目录执行(pm2 是全局命令,不依赖当前目录,仅启动相对路径脚本时除外)。

四、进程管理命令详解

本章覆盖日常操作频率最高的进程生命周期命令。统一验证手法:操作后用 pm2 list 看进程表状态、用 curl -s http://localhost:3000/ 看业务返回中的 PID。

4.1 pm2 start:启动应用

start 负责把脚本交给 pm2 守护进程托管,支持 fork 与 cluster 两种模式。最基础的 fork 模式启动:

cd /opt/demoapp
pm2 start app.js --name app

实测回显:

[PM2] Starting /opt/demoapp/app.js in fork_mode (1 instance)
[PM2] Done.

对 HTTP 服务推荐 cluster 模式多实例启动(-i 2 即 2 个实例,内置负载均衡):

pm2 start app.js -i 2 --name web

实测回显:

[PM2] Starting /opt/demoapp/app.js in cluster_mode (2 instances)
[PM2] Done.

start 常用参数(均可与 --help 中的全局参数组合):

参数作用示例
--name <名>指定进程列表中的应用名pm2 start app.js --name app
-i <N>cluster 模式实例数,max 等于 CPU 核数pm2 start app.js -i 2
--max-memory-restart <内存>内存超限自动重启(如 60M)pm2 start app.js --max-memory-restart 60M
--time日志行前加时间戳pm2 start app.js --time
--watch监听文件变更自动重启pm2 start app.js --watch

启动后立即验证进程表与服务(连续请求 4 次,观察 cluster 模式的负载均衡轮换):

pm2 list
curl -s http://localhost:3000/
curl -s http://localhost:3000/
curl -s http://localhost:3000/
curl -s http://localhost:3000/

实测回显(cluster 2 实例):

┌────┬────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name   │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├────┼────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0  │ web    │ default     │ N/A     │ cluster │ 3650     │ 0s     │ 0    │ online    │ 0%       │ 58.8mb   │ root     │ disabled │
│ 1  │ web    │ default     │ N/A     │ cluster │ 3657     │ 0s     │ 0    │ online    │ 0%       │ 45.9mb   │ root     │ disabled │
└────┴────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
Hello from pm2 demo app, PID=3650
Hello from pm2 demo app, PID=3657
Hello from pm2 demo app, PID=3650
Hello from pm2 demo app, PID=3657

两个实例 PID 3650/3657 轮流响应请求——cluster 模式端口由主进程统一绑定、按轮询分发给 worker 的直观验证。pm2 list 各列含义:mode(fork/cluster 执行模式)、↺(不稳定重启计数)、status(online/stopped/errored/launching)、watching(是否开启文件监听)。

4.2 pm2 list / status:查看进程列表

list(别名 ls、ps、status)输出全部托管进程。对已存在的应用执行 pm2 start <应用名> 并不是报错,而是触发一次重启(实测回显 [PM2] Applying action restartProcessId),即「存在则重启、不存在则报未知应用」。

pm2 status

实测回显:

┌────┬────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name   │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├────┼────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0  │ web    │ default     │ N/A     │ cluster │ 3650     │ 1s     │ 0    │ online    │ 0%       │ 58.8mb   │ root     │ disabled │
│ 1  │ web    │ default     │ N/A     │ cluster │ 3657     │ 1s     │ 0    │ online    │ 0%       │ 45.9mb   │ root     │ disabled │
└────┴────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

4.3 pm2 show / describe:单应用全量详情

show(别名 describe、info)输出单应用的全量元数据与运行指标:

pm2 show web

实测回显(输出节选,实测首尾):

 Describing process with id 0 - name web
┌───────────────────┬─────────────────────────────────┐
│ status            │ online                          │
│ name              │ web                             │
│ namespace         │ default                         │
│ version           │ N/A                             │
│ restarts          │ 1                               │
│ uptime            │ 14s                             │
│ script path       │ /opt/demoapp/app.js             │
│ script args       │ N/A                             │
│ error log path    │ /root/.pm2/logs/web-error-0.log │
│ out log path      │ /root/.pm2/logs/web-out-0.log   │
│ pid path          │ /root/.pm2/pids/web-0.pid       │
│ interpreter       │ node                            │
│ script id         │ 0                               │
│ exec cwd          │ /opt/demoapp                    │
│ exec mode         │ cluster_mode                    │
│ node.js version   │ 22.23.3                         │
│ node env          │ N/A                             │
│ watch & reload    │ ✘                               │
│ unstable restarts │ 0                               │
│ created at        │ 2026-10-18T10:19:39.865Z        │
└───────────────────┴─────────────────────────────────┘
...
 Code metrics value
┌────────────────────────┬──────────────┐
│ Heap Size              │ 8.60 MiB     │
│ Heap Usage             │ 71.35 %      │
│ Used Heap Size         │ 6.14 MiB     │
│ Active requests        │ 0            │
│ Active handles         │ 4            │
│ Event Loop Latency     │ 0.18 ms      │
│ Event Loop Latency p95 │ 0.87 ms      │
│ HTTP Mean Latency      │ 1 ms         │
│ HTTP P95 Latency       │ 1 ms         │
│ HTTP                   │ 0.01 req/min │
└────────────────────────┴──────────────┘

解读:上半段是进程身份与路径信息(日志路径、执行模式、Node 版本),下半段 Code metrics 是内嵌探针采集的运行时指标(堆内存、事件循环延迟、HTTP 延迟分位数),排障时先看这里。

4.4 pm2 stop:停止应用

pm2 stop app

实测回显:

[PM2] Applying action stopProcessId on app [app](ids: [ 0 ])
[PM2] [app](0) ✓

stop 后进程条目保留、状态变 stopped、业务端口关闭。验证:

pm2 list | grep app
curl -s -m 2 http://localhost:3000/ || echo "连接被拒绝,端口已关闭"

实测回显:

│ 0  │ app    │ default     │ N/A     │ fork    │ 0        │ 0      │ 1    │ stopped   │ 0%       │ 0b       │ root     │ disabled │
连接被拒绝,端口已关闭

💡 说明:pm2 stop all 可一次停止全部应用;stop 只停进程不删条目,重新拉起用 pm2 start app(实测回显 [PM2] Applying action restartProcessId,start 对已存在应用等效于重启)。

4.5 pm2 restart:重启应用

pm2 restart app

实测回显:

Use --update-env to update environment variables
[PM2] Applying action restartProcessId on app [app](ids: [ 0 ])
[PM2] [app](0) ✓

restart 是「杀掉旧进程 + 重新拉起」,服务会有短暂中断;重启计数 ↺ 加 1(实测重启后 pm2 list 中 app 条目 ↺ 从 0 变 1)。首行提示值得记住:restart 默认不刷新环境变量,改了系统环境或 ecosystem 中的 env 后必须用 pm2 restart app --update-env(见 9.2 FAQ)。

4.6 pm2 reload:零停机重载(cluster 专用)

reload 只对 cluster 模式应用有意义:逐个替换 worker,任一时刻都有存活实例在接请求。实测验证「reload 全程服务不中断」:

pm2 reload web
curl -s http://localhost:3000/
curl -s http://localhost:3000/

实测回显:

Use --update-env to update environment variables
[PM2] Applying action reloadProcessId on app [web](ids: [ 0, 1 ])
[PM2] [web](0) ✓
[PM2] [web](1) ✓
Hello from pm2 demo app, PID=3704
Hello from pm2 demo app, PID=3704

reload 前实例 PID 为 3650/3657,reload 后变为 3704/3717(pm2 list 实测),而 reload 完成后的 curl 请求立刻返回新实例的正常响应——发布代码的标准姿势就是「更新代码 → pm2 reload web」。fork 模式单实例应用执行 reload 等价于 restart,会有中断。

4.7 pm2 delete:删除应用

pm2 delete app

实测回显:

[PM2] Applying action deleteProcessId on app [app](ids: [ 0 ])
[PM2] [app](0) ✓

delete = stop + 从进程列表移除,条目消失后 pm2 save 固化的清单也会随之变化(需重新 save)。

4.8 pm2 scale:调整 cluster 实例数

pm2 scale web 4

实测回显:

[PM2] Scaling up application
[PM2] Scaling up application

实测 pm2 list 确认实例从 2 个扩到 4 个(id 0~3 均 online):

│ 0  │ web    │ default     │ N/A     │ cluster │ 3704     │ 1s     │ 1    │ online    │ 0%       │ 61.1mb   │ root     │ disabled │
│ 1  │ web    │ default     │ N/A     │ cluster │ 3717     │ 1s     │ 1    │ online    │ 0%       │ 61.3mb   │ root     │ disabled │
│ 2  │ web    │ default     │ N/A     │ cluster │ 3750     │ 0s     │ 0    │ online    │ 0%       │ 58.6mb   │ root     │ disabled │
│ 3  │ web    │ default     │ N/A     │ cluster │ 3757     │ 0s     │ 0    │ online    │ 0%       │ 45.9mb   │ root     │ disabled │

scale 只适用于 cluster 模式;传比当前小的数字即缩容。

4.9 pm2 pid / id:取进程号与应用编号

pm2 pid demo-eco
pm2 id demo-eco

实测回显(demo-eco 为 cluster 2 实例应用):

8221
8222
[ 0, 1 ]

pid 按实例逐行输出操作系统进程号(单实例应用输出一行),id 输出 pm2 内部的 pm_id 列表,脚本中常用它们定位目标。

五、日志与监控命令

5.1 pm2 logs:查看与跟随日志

默认流式跟随全部应用日志;--lines N 回看最近 N 行,--nostream 只打印不跟随(适合脚本与归档场景),应用名做参数则只看该应用:

pm2 logs web --lines 3 --nostream

实测回显:

[TAILING] Tailing last 3 lines for [web] process (change the value with --lines option)
/root/.pm2/logs/web-error-0.log last 3 lines:
/root/.pm2/logs/web-out-0.log last 3 lines:
0|web      | demo app listening on port 3000, PID=3650
0|web      | demo app listening on port 3000, PID=3657

日志行前缀 0|web 表示「pm_id=0 的 web 应用实例」。cluster 多实例时每个实例各写一份带编号的日志文件(web-out-0.log、web-out-1.log),除非在配置中开启 merge_logs 合并(见《pm2 7.0.4 配置参数详解》)。

5.2 pm2 flush:清空日志

pm2 flush

实测回显:

[PM2] Flushing /root/.pm2/pm2.log
[PM2] Flushing:
[PM2] /var/log/demoapp/out.log
[PM2] /var/log/demoapp/error.log
[PM2] Flushing:
[PM2] /var/log/demoapp/out.log
[PM2] /var/log/demoapp/error.log
[PM2] Flushing:
[PM2] /root/.pm2/logs/leaker-out.log
[PM2] /root/.pm2/logs/leaker-error.log
[PM2] Flushing:
[PM2] /root/.pm2/logs/crasher-out.log
[PM2] /root/.pm2/logs/crasher-error.log
[PM2] Logs flushed

flush 会把守护进程日志与所有应用日志清零(文件保留、内容清空),磁盘被日志占满时的应急手段;长期治理应配置 logrotate(pm2 logrotate 安装按天轮转配置)。

5.3 pm2 monit / dashboard:终端交互式监控

pm2 monit 与 pm2 dashboard 是终端交互式全屏界面(TUI):monit 展示各应用 CPU/内存实时柱状与历史曲线,可上下键选中应用查看;dashboard 在 monit 基础上叠加实时日志流。两者均为 termcaps 交互界面,需在真实终端中运行、按 q 或 Ctrl+C 退出,本文无法以非交互方式截取界面回显。

脚本化或无终端场景的等价替代:

# 进程表快照(含 CPU/内存列)
pm2 list
# 单应用运行时指标(堆、事件循环延迟、HTTP 延迟)
pm2 show web
# 系统资源 JSON 快照
pm2 slist

5.4 pm2 jlist / prettylist:脚本化 JSON 输出

jlist 输出全部进程的完整 JSON(单行,供 jq/python 等解析),prettylist 输出缩进美化版(便于人工阅读):

pm2 jlist | head -c 400

实测回显(原始 JSON 前 400 字节):

[{"pid":3704,"name":"web","pm2_env":{"name":"web","filter_env":[],"namespace":"default","env":{"HOSTNAME":"...","PWD":"/opt/demoapp","HOME":"/root","SHLVL":"1","PATH":"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","_":"/usr/bin/pm2","OLDPWD":"/","PM2_USAGE":"CLI","PM2_HOME":"/root/.pm2","web":{},"unique_id":"b26ccb3b-4d96-4711-8988-5977ab3cca5b"},"instances":2,"vizion":true,"autostart":true,"autorestart":true,"watch":false,
pm2 prettylist

实测回显(输出节选,实测首尾):

[
  {
    pid: 3704,
    name: 'web',
    pm2_env: {
      name: 'web',
      filter_env: [],
      namespace: 'default',
      env: {
        ...
      },
      instances: 2,
      vizion: true,
      autostart: true,
      autorestart: true,
      watch: false,
      instance_var: 'NODE_APP_INSTANCE',
      pmx: true,
      automation: true,
      treekill: true,
      username: 'root',
      windowsHide: true,
      kill_retry_time: 100,
      node_args: [],
      pm_exec_path: '/opt/demoapp/app.js',
      pm_cwd: '/opt/demoapp',
      exec_interpreter: 'node',
      exec_mode: 'cluster_mode',
      pm_out_log_path: '/root/.pm2/logs/web-out-0.log',
      pm_err_log_path: '/root/.pm2/logs/web-error-0.log',
...

💡 说明:jlist 的 JSON 结构中 pm2_env 就是该应用的完整生效配置(执行模式、日志路径、实例数、自愈开关等),是核对「配置是否真的生效」的最权威依据——配置文件详解篇中的参数验证均以此为最终裁判。

5.5 pm2 slist:系统信息

pm2 slist

实测回显(输出节选,实测首尾):

{
  'CPU Usage': { value: 10.6, type: 'metric', unit: '%', historic: true },
  'RAM Usage': { value: 58.5, type: 'metric', unit: '%', historic: true },
  'RAM Total': { value: 33607307264, type: 'metric', unit: 'b', historic: true },
  'RAM Available': { value: 13952000000, type: 'metric', unit: 'b', historic: true },
  'net:rx_5:eth0': { value: 0, type: 'metric', unit: 'mb/s', historic: true },
  'Disk Reads': { value: 0.002, type: 'metric', unit: 'mb/s', historic: true },
  'Disk Writes': { value: 1.027, type: 'metric', unit: 'mb/s', historic: true },
  'fs:use:/etc/hosts': { value: 28.38, type: 'metric', unit: '%', historic: true },
  'fs:size:/etc/hosts': { value: 785.88, type: 'metric', unit: 'gb', historic: true }
}

slist 输出宿主机 CPU/内存/网卡/磁盘指标,与 pm2 list 表头下方的 host metrics 行同源,适合并入监控采集脚本。

5.6 pm2 env:查看应用生效环境变量

pm2 env 0 | grep -E "^(NODE_ENV|PORT):"

实测回显(应用以 env_production 启动时):

NODE_ENV: production
PORT: 3001

pm2 env <pm_id> 输出该应用进程的完整环境变量,多环境配置(env / env_production)排查首选——变量是否真的注入以它为准。

六、持久化与开机自启命令

这组命令维护 pm2 的「进程清单」并对接系统 init,完整实测步骤见《Ubuntu 22.04 安装 pm2 7.0.4 指南》第七章,此处给出命令语义与关键回显:

命令作用实测关键回显
pm2 save把当前进程列表写入 ~/.pm2/dump.pm2[PM2] Successfully saved in /root/.pm2/dump.pm2
pm2 resurrect按 dump 清单恢复全部应用(systemd 开机调用的正是它)[PM2] Resurrecting + 逐应用 launched
pm2 startup [platform]生成并启用开机自启系统服务[PM2] Init System found: systemd + Created symlink ... pm2-root.service
pm2 unstartup [platform]撤销 startup 生成的服务[PM2] Init file disabled.
pm2 update升级 pm2 包后让守护进程换到新版本并恢复应用逐应用 restartProcessId + 进程表
pm2 kill停止全部应用并杀掉 pm2 守护进程[PM2] [v] All Applications Stopped / [PM2] [v] PM2 Daemon Stopped
pm2 ping探活守护进程(不存在则拉起){ msg: 'pong' }
pm2 cleardump生成空 dump 文件(清空恢复清单)重写 dump.pm2 为空清单

⚠️ 注意:pm2 kill 之后守护进程消失,下次执行任意 pm2 命令时会自动重新拉起(实测 pm2 start 回显 [PM2] Spawning PM2 daemon with pm2_home=/root/.pm2)。kill 常用于守护进程状态异常时的「重启大法」,但注意 kill 后需重新 pm2 start 应用或 pm2 resurrect。

七、全局参数速查

以下为 pm2 --help 中使用频率最高的全局参数(原文照抄),可挂在 start/restart 等子命令后:

参数原文说明备注
-n, --name <name>set a name for the process in the process liststart 时指定应用名
-i, --instances <number>launch [number] instances (for networked app)(load balanced)cluster 模式实例数
-o, --output <path>specify log file for stdout覆盖 stdout 日志路径
-e, --error <path>specify log file for stderr覆盖 stderr 日志路径
-l, --log [path]specify log file which gathers both stdout and stderrout+err 合并到单文件
--timeenable time logging日志加时间戳
--log-date-format <date format>add custom prefix timestamp to logs自定义时间戳格式
--max-memory-restart <memory>Restart the app if an amount of memory is exceeded (in bytes)支持 60M/1G 形式
--restart-delay <delay>specify a delay between restarts (in milliseconds)重启间隔防风暴
--max-restarts [count]only restart the script COUNT times限制重启次数
-c, --cron <cron_pattern>restart a running process based on a cron pattern定时重启
--watch [paths]watch application folder for changes (default: )文件变更自动重启
--merge-logsmerge logs from different instances but keep error and out separated多实例日志合并
--no-autorestartstart an app without automatic restart关闭崩溃自启
--env <environment_name>specify which set of environment variables from ecosystem file must be injected多环境注入
-a, --update-envforce an update of the environment with restart/reload (-a <=> apply)restart/reload 时刷新环境变量
-f, --forceforce actions强制执行
-s, --silenthide all messages静默模式
-h, --helpoutput usage information帮助

八、注意事项

  • restart 与 reload 的取舍:非网络类 worker 用 restart;HTTP/HTTPS 网络服务在 cluster 模式下用 reload 做发布(零停机),两者实测行为差异见 4.5/4.6;
  • 环境变量惯性:restart/reload 默认沿用启动时快照的环境变量,改动系统环境或 ecosystem 后必须 --update-env,否则「改了不生效」;
  • save 的时机:进程清单的任何结构性变化(新增/删除/改名)之后都要 pm2 save,否则开机恢复的是旧清单;
  • 日志双写:应用自身的 console 输出会同时进入 pm2 日志文件,应用若再自行写文件日志会造成双份,二选一即可;
  • 交互式命令:monit/dashboard 为 TUI 界面,脚本与 CI 中用 list/show/jlist 替代。

九、常见问题(FAQ)

Q1:pm2 restart 后应用行为没变,像是没读到新配置? 现象:修改了环境变量或 ecosystem 配置后 restart,应用行为依旧。定位:restart 默认沿用启动时的环境快照,实测回显首行即提示 Use --update-env to update environment variables。解决:

pm2 restart web --update-env

实测回显:

Use --update-env to update environment variables
[PM2] Applying action restartProcessId on app [web](ids: [ 0, 1 ])
[PM2] [web](0) ✓
[PM2] [web](1) ✓

生效核对用 pm2 env <pm_id>(见 5.6)。

Q2:pm2 start app(应用已存在)报错还是重启? 结论:等价于重启,不是报错。实测回显:

[PM2] Applying action restartProcessId on app [app](ids: [ 0 ])
[PM2] [app](0) ✓

应用不存在时才会报 [PM2][ERROR] Process app not found。

Q3:应用状态显示 errored 怎么排查? 定位三步:先 pm2 describe <应用名> 看 script path/exec cwd 是否正确、unstable restarts 是否持续增长;再看应用错误日志 pm2 logs <应用名> --err --lines 50(或直接看 ~/.pm2/logs/<应用名>-error.log);最后看守护进程日志 ~/.pm2/pm2.log(内存超限重启等事件记录在此,实测形如 PM2 log: [PM2][WORKER] Process 2 restarted because it exceeds --max-memory-restart value (current_memory=166830080 max_memory_limit=62914560 [octets]))。常见根因:端口被占用(EADDRINUSE,实测错误日志形如 syscall: 'listen', port: 3000)、脚本路径错误、依赖缺失。

Q4:怎么只看某个应用的错误日志?

pm2 logs web --err --lines 20 --nostream

实测回显(应用无错误时输出为空列表):

[TAILING] Tailing last 20 lines for [web] process (change the value with --lines option)
/root/.pm2/logs/web-error-0.log last 20 lines:

十、参考链接