PM2学习日志(1)

512 阅读3分钟

什么是PM2

  • PM2全称为ProcessManager2 不清楚是否有1...

PM2 is daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via NPM.

PM2是一个守护进程的管理器,可以帮助您管理并且保持应用在线。使用PM2非常简单,它是一个简单且直观的CLI,可以通过NPM安装

npm install pm2@least -g

PM2能做什么

  • 管理,监控应用程序
  • 自动重载
  • 日志收集
  • 内置负载均衡

如何使用PM2

  • 启动一个Node应用
pm2 start app.js
  • PM2常用命令
# 重启
pm2 restart app_name

# 重载 
pm2 reload app_name

# 停止
pm2 stop app_name

# 删除
pm2 delete app_name

# 检查状态
pm2 list|ls|status

# 开启内置的监控仪表板
pm2 monit

# 更新PM2
pm2 update

执行完PM2会打印当前PM2管理的所有进程实例,包含id,名称,模式,状态,cpu使用率,内存使用率

下载 1.png

app_name 可以是其他参数而不是名称,符合的参数`name|id|script|all|json|stdin'

  • name 名称 可以通过 参数 --name指定, 空缺默认使用执行的文件名
  • id pm2内部id
  • script 可以通过js脚本执行
  • all 所有
  • json 可以通过json执行
  • stdin 标准输入
  • PM2常用参数
# 指定应用名称
--name <app_name>

# 监控文件的变化并自动重启应用
--watch

# 忽略监控变化的目录
--ignore-watch

# 最大内存阈值, 触发自动重启
--max-memory-restart <200MB>

# 日志输出路径
--log <log_path>

# 应用的启动参数 例如: --port=xxxx
-- arg1 arg2 arg3

# 重启延迟
--restart-delay <delay in ms>

# 在输出的日志前加上时间
--time

# 不自动重启
--no-autorestart

# 使用Cron表达式控制应用的重启时间
--cron <cron_pattern>

# 如果pm2后台程序不存在,则在前台运行它
--no-daemon

如何优雅的关闭

In production environment, you may need to wait for remaining queries to be processed or close all connections before exiting the application. On the PM2 reload context it can be translated into a very long reload or a reload that doesn’t work (fallback to restart) meaning that your application still has open connections on exit. You may alternatively need to close all databases connections, clear data queues or whatever.

在生产环境中,您可能需要等待处理剩余的查询,或者在退出应用程序之前关闭所有连接。 在 PM2重新加载上下文中,它可以转化为一个非常长的重新加载或不工作的重新加载(后退重新启动) ,这意味着您的应用程序在退出时仍然有打开的连接。 您还可能需要关闭所有数据库连接、清除数据队列或其他操作。

To Gracefully Shutdown an application you can catch the SIGINT signal (the first signal sent on exit by PM2) and execute actions to wait/clear all these states:

要优雅地关闭一个应用程序,你可以捕获 SIGINT 信号(PM2在退出时发出的第一个信号)并执行操作来等待 / 清除所有这些状态:

注意: 需要配合 --shutdown_with_message使用

process.on('message', function(msg) {
  if (msg == 'shutdown') {
    console.log('Closing all connections...');
    setTimeout(function() {
      console.log('Finished closing connections');
      process.exit(0);
    }, 1500);
  }
});

参考资料