pm2 官方文档 学习笔记

介绍

 

PM2进程管理器,是一种应用程序“容器”,用于促进部署,提供高可用性,并支持用户在运行时管理应用程序。

除了 PM2,还有类似的工具:

  • StrongLoop Process Manager

  • Forever

这里不做过多介绍,待写。

一、安装#


1、安装#


Copynpm install pm2 -g

2、更新#


Copynpm install pm2 -g && pm2 update

pm2 update 是为了刷新 PM2 的守护进程

二、使用 js 配置文件启动#


1、生成配置文件#


Copypm2 ecosystem

会自动生成 ecosystem.config.js 文件 (下文的 "五、配置文件实例" 会详细说到如何配置)

2、启动配置文件#


Copypm2 start /path/ecosystem.config.js 
Copypm2 start /path/ecosystem.config.js -i max
// PM2 将自动检测可用 CPU 的数量并运行尽可能多的进程

三、管理 PM2 进程#


1、常规#


Copypm2 start
​
pm2 restart
​
pm2 reload
​
pm2 ls
​
pm2 stop
​
pm2 delete
restart` vs `reload

restart:pm2 同时杀死并重启所有进程。短时间内服务不可用

reload:pm2 逐个重启所有进程,但始终保持至少一个进程在运行

所以推荐使用 reload

2、操作多个进程#


写法一:

Copypm2 restart / reload / stop / delete app1 app2 app3

写法二:

Copypm2 restart / reload / stop / delete all

node.js 中如何判断当前程序执行的是哪个进程?

使用 NODE_APP_INSTANCE 环境变量

Copyif(process.env.NODE_APP_INSTANCE === 0){
    //todo
}

多个进程相互独立,若需要共享某些数据,可使用 Redis 。

3、保存 / 恢复进程 list#


Copy# save your list in hard disk memory
pm2 save
​
# resurrect your list previously saved
pm2 resurrect

4、监视进程#


Copypm2 monit

5、使主机重启后可以恢复之前的进程#


Copypm2 startup
//在 CLI 中复制并粘贴此命令的输出以设置启动挂钩
​
pm2 unstartup

四、日志#


Copy# all apps logs
pm2 logs
​
# only app logs
pm2 logs app
​
# 加上 [--err | --out],可以分别只列出 out 或 err 部分

五、配置文件实例#


Copy
module.exports = {
  /**
   * Application configuration section
   * http://pm2.keymetrics.io/docs/usage/application-declaration/
   */
  apps: [
​
    // First application
    {
      name: 'UB',
      script: './bin/www',
      instances: "max",
      exec_mode: "cluster",
      env: {
        NODE_ENV: 'development'
      },
      env_testing: {
        NODE_ENV: 'testing'
      },
      env_production: {
        NODE_ENV: 'production'
      },
    //   log combines output and error, disabled by default
    //   "log": "./logs/combined.log", 
      "error_file": "./logs/pm2_UB_err.log",
      "out_file": "./logs/pm2_UB_out.log",
    //   In cluster mode, each cluster has his own log files. You can use the merge options to gather all logs into a single file
      "merge_logs": true, 
    //   "log_type":"json"
      "log_date_format": "YYYY-MM-DD HH:mm:ss Z"
    },
​
    // Second application
    {
      name: 'UB_schedule',
      script: './campaign_schedule.js',
      "error_file": "./logs/pm2_UB_schedule_err.log",
      "out_file": "./logs/pm2_UB_schedule_out.log",
      "merge_logs": true,
      "log_date_format": "YYYY-MM-DD HH:mm:ss Z"
    }
  ],
​
  /**
   * Deployment section
   * http://pm2.keymetrics.io/docs/usage/deployment/
   */
  deploy: { 
​
    testing: {
      user: 'universe',
      host: 'xxx.xx.93.179',
      ssh_options: "StrictHostKeyChecking=no",
      ref: 'origin/backend-api',
      repo: 'git@gitlab.example.com:production-team/universal_backend.git',
      path: '/home/universe/universalapi',
​
      //    pre-deploy action (为了填坑,下文有述)
      'pre-deploy': "git fetch", 
      'post-deploy': 'npm install --registry=https://registry.npm.taobao.org && pm2 startOrRestart ecosystem.config.js --env testing',
    },
​
    production: {
    //   SSH key path, default to $HOME/.ssh
    //   key: "/path/to/some.pem",
      // SSH user
      user: 'universe',
      // SSH host
      host: ['xxx.xx.103.209', 'xxx.xx.98.216', 'xxx.xx.61.173'],
    //   SSH options with no command-line flag, see 'man ssh'
    //   can be either a single string or an array of strings
      ssh_options: "StrictHostKeyChecking=no",
    //   GIT remote/branch
      ref: 'origin/backend-api',
    //   GIT remote
      repo: 'git@gitlab.example.com:production-team/universal_backend.git',
    //   path in the server
      path: '/home/universe/xxx',
​
    //   Pre-setup command or path to a script on your local machine
      'pre-setup': "yum install git ; ls -la",
    //   Post-setup commands or path to a script on the host machine
    //   eg: placing configurations in the shared dir etc
      'post-setup': "ls -la",
​
    //    pre-deploy action (为了填坑,下文有述)
      'pre-deploy': "git fetch",
    //   post-deploy action
      'post-deploy': 'npm install --registry=https://registry.npm.taobao.org && pm2 startOrRestart ecosystem.config.js --env production',
    }
​
  }
​
};

这里定义了 development | testing | production 三个环境变量

如何指定环境变量:

Copy//启动
pm2 start ecosystem.config.js --env production
​
//更新
pm2 restart ecosystem.config.js --env production --update-env

nodejs中如何使用环境变量:

process.env.[环境变量]
Copyif (process.env.NODE_ENV == "production") {
​
} else if (process.env.NODE_ENV == "testing") {
   
} else if (process.env.NODE_ENV == "development") {
   
} else {
    
}

3、deploy 部署#

img

(1)前期准备:

a.本机:

1.安装 pm2 / git

2.跟 github 做好 ssh 授权登录(使用 密钥认证 方式)

b.远程主机:

1.安装 pm2 / git

2.跟 github 做好 ssh 授权登录(使用 密钥认证 方式)

c.本机 和 远程主机 做好 ssh 授权登录(使用 密钥认证 方式)

关于“github 做好 ssh 授权登录”,详见我的另一篇《 SSH 学习笔记

(2)先 setup

Copypm2 deploy ecosystem.config.js production setup

实质:执行了 git clone 的操作

(3)再 deploy

Copypm2 deploy ecosystem.config.js production

实质:执行了 git fetch 的操作


(4)其他操作

Copy# Update remote version
pm2 deploy production update
​
# Revert to -1 deployment
pm2 deploy production revert 1
​
# execute a command on remote servers
pm2 deploy production exec "pm2 reload all"

(5)强制部署

如果你在本地修改了 ecosystem.config.js却没有 push 到 github 上,这个时候 deploy 会报错:

Copy--> Deploying to dev environment
--> on host 192.168.1.XX
​
  push your changes before deploying
​
Deploy failed

这时就可以使用到强制部署

Copypm2 deploy ecosystem.config.js production --force 

注:--force 只对 ecosystem.config.js 配置中的 “deploy” 部分有效,“apps” 部分依然是以 github 为准


填坑:#

坑1、deploy的时候远程服务器不会拉取github上最新的commit

原因: https://github.com/Unitech/pm2/issues/2935

@nukosuke: Probably, it's caused by git. If you execute git fetch with depth option by using Git v1.8, fetch doesn't work in the worktree. Use git v1.9 or later.

解决方案:

手动加上

Copy'pre-deploy': "git fetch",

参考资料:

1.【 pm官方文档 】https://pm2.io/doc/en/runtime/guide/installation/#install-pm2

posted @ 2020-03-25 11:28  江湖艺人  阅读(545)  评论(0编辑  收藏  举报