关于 pm2
一项介绍 PM2 的技能,用于持续运行服务、工作进程和 Agent,并通过进程管理、崩溃重启、日志与监控维护运行状态。
主要功能
- 01启动和管理进程
- 02崩溃后自动重启
- 03监控 CPU、内存和日志
- 04配置多进程应用
- 05保存并恢复进程列表
适用场景
- 01持续运行后台工作进程
- 02将 Agent 作为常驻服务运行
- 03检查进程健康状态和重启次数
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ marcfargas/ skills --skill pm2安装后在 Claude Code 中输入/pm2确认已加载。
详细介绍
PM2 — 进程管理器
PM2 可保持进程运行,在进程崩溃时重启,并提供监控和日志功能。 适用于长时间运行的服务、持久化 Agent 和后台工作进程。
不适用于分离的终端会话 — 如果需要 PTY 输出、附加/查看或交互式会话,请使用 holdpty。 不适用于临时任务 — 可使用
pi -p > file &快速启动即发即弃的 Agent 运行。
快速参考
启动进程
# Simple
pm2 start server.js --name myapp
# With interpreter
pm2 start script.py --interpreter python3 --name worker
# With arguments (use -- to separate pm2 args from script args)
pm2 start app.js --name api -- --port 3000 --env production
# From ecosystem file
pm2 start ecosystem.config.cjs
管理进程
pm2 list # List all processes (table)
pm2 jlist # List as JSON (for scripting)
pm2 info <name|id> # Detailed process info
pm2 restart <name|id|all> # Restart
pm2 stop <name|id|all> # Stop (keeps in list)
pm2 delete <name|id|all> # Stop + remove from list
pm2 restart <name> --update-env # Restart with refreshed env vars
日志
pm2 logs # Tail all logs
pm2 logs <name> --lines 50 # Tail specific process, last 50 lines
pm2 flush # Clear all log files
日志文件位置:~/.pm2/logs/<name>-out.log 和 <name>-error.log。
监控
pm2 monit # Real-time TUI: CPU, memory, logs
pm2 dash # Dashboard with monitoring + logs
Ecosystem 配置
如需可重复的多进程配置,请使用 ecosystem.config.cjs 文件:
// ecosystem.config.cjs
module.exports = {
apps: [
{
name: "api",
script: "dist/server.js",
instances: 2, // cluster mode
exec_mode: "cluster",
env: {
NODE_ENV: "production",
PORT: 3000,
},
max_memory_restart: "500M",
log_date_format: "YYYY-MM-DD HH:mm:ss",
},
{
name: "worker",
script: "dist/worker.js",
autorestart: true,
max_restarts: 10,
restart_delay: 5000,
exp_backoff_restart_delay: 100, // exponential backoff
watch: false,
},
],
};
pm2 start ecosystem.config.cjs # Start all apps
pm2 start ecosystem.config.cjs --only api # Start specific app
pm2 restart ecosystem.config.cjs # Restart all
pm2 delete ecosystem.config.cjs # Stop + remove all
实用的 ecosystem 选项
| 选项 | 类型 | 描述 |
|---|---|---|
script | string | 要运行的脚本(必填) |
interpreter | string | 覆盖解释器(默认值:node) |
args | string or string[] | 脚本参数 |
cwd | string | 工作目录 |
instances | number | 实例数量(集群模式) |
exec_mode | string | "fork"(默认值)或 "cluster" |
autorestart | boolean | 退出时自动重启(默认值:true) |
max_restarts | number | 停止前连续重启的最大次数 |
restart_delay | number | 重启间隔(ms) |
exp_backoff_restart_delay | number | 指数退避基准值(ms) |
max_memory_restart | string | 内存超出时重启(例如 "500M") |
cron_restart | string | 基于 Cron 的重启计划 |
watch | boolean or string[] | 监视文件更改 |
ignore_watch | string[] | 监视时忽略的路径 |
env | object | 环境变量 |
log_date_format | string | 日志的时间戳格式 |
error_file | string | 自定义 stderr 日志路径 |
out_file | string | 自定义 stdout 日志路径 |
merge_logs | boolean | 合并集群实例日志 |
stop_exit_codes | number[] | 跳过自动重启的退出代码 |
持久化
pm2 save # Save current process list
pm2 resurrect # Restore saved process list
pm2 startup # Generate OS startup script (auto-start on boot)
pm2 unstartup # Remove startup script
运行 pm2 startup 后,执行它输出的命令(可能需要管理员权限或 sudo)。
然后运行 pm2 save 快照保存当前进程,这些进程将在重启时自动启动。
Windows 注意事项
.cmd 包装器解析
PM2 会尝试将 .cmd 文件作为 Node.js 脚本运行。切勿直接用 PM2 启动 .cmd 垫片。
# ❌ WRONG — resolves to pi.cmd, crashes
pm2 start pi -- -p "prompt"
# ✅ CORRECT — point to the actual .js entry point
pm2 start /path/to/cli.js --interpreter node -- -p "prompt"
对于通过 npm 安装的 CLI,请查找实际脚本:
# Find where the .cmd shim points
cat "$(which pi)" | head -5
# → Look for the .js path, then use that with --interpreter node
在 ecosystem 配置中,始终使用解析后的 .js 路径:
module.exports = {
apps: [{
name: "my-agent",
// Resolve the actual cli.js, not the .cmd wrapper
script: "C:\\path\\to\\node_modules\\package\\dist\\cli.js",
interpreter: "node",
args: ["--mode", "json"],
}],
};
日志路径
PM2 将日志存储在 ~/.pm2/logs/。在 Windows 上,该路径通常为 C:\Users\<user>\.pm2\logs\。
守护进程
PM2 守护进程以后台 Node.js 进程的形式运行。pm2 kill 会停止守护进程及其管理的所有进程。pm2 ping 用于检查守护进程是否正在运行。
Agent 模式
将 pi Agent 作为持久化服务启动
首先,查找实际的 cli.js 路径(参见上文“Windows 注意事项”):
# Find pi's real entry point
cat "$(which pi)" | head -5
# e.g. → /path/to/node_modules/@mariozechner/pi-coding-agent/dist/cli.js
// ecosystem.config.cjs
module.exports = {
apps: [{
name: "my-agent",
// Use the resolved cli.js path — NOT the .cmd wrapper
script: "/path/to/node_modules/@mariozechner/pi-coding-agent/dist/cli.js",
interpreter: "node",
args: ["--mode", "json", "--cwd", "/path/to/project"],
autorestart: true,
max_restarts: 10,
restart_delay: 5000,
}],
};
注意:
pi -p在非 TTY 环境下只会输出最终文本。使用--mode json可将完整事件流输出到 PM2 日志。
从 Agent 检查进程健康状况
# Structured output for parsing
pm2 jlist | node -e "
const d = JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'));
d.forEach(p => console.log(p.name, p.pm2_env.status, 'restarts:', p.pm2_env.restart_time));
"
轮转日志
pm2 install pm2-logrotate # Install log rotation module
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 5
不适合使用 PM2 的情况
- 分离的终端会话 → 使用 holdpty(PTY 输出、附加/查看)
- 临时 Agent 运行 → 使用
pi -p > file &(即发即弃并捕获输出) - 容器 → 容器运行时负责管理生命周期;在 Docker 中使用 PM2 通常是多余的
- Systemd 环境 → 在 Linux 上原生使用 systemd 服务单元