PM2高级Node进程管理器

PM2是nodejs的进程管理器,内置了一个进程负载均衡器,让你的应用一直保持运行,也可以辅助系统管理管理服务器

Behavior configuration行为配置

{
  "apps" : [{
    // Application #1
    "name"        : "worker-app",
    "script"      : "worker.js",
    "args"        : ["--toto=heya coco", "-d", "1"],
    "watch"       : true,
    "node_args"   : "--harmony",
    "merge_logs"  : true,
    "cwd"         : "/this/is/a/path/to/start/script",
    "env": {
      "NODE_ENV": "development",
      "AWESOME_SERVICE_API_TOKEN": "xxx"
    },
    "env_production" : {
       "NODE_ENV": "production"
    },
    "env_staging" : {
       "NODE_ENV" : "staging",
       "TEST"     : true
    }
  },{
    // Application #2
    "name"       : "api-app",
    "script"     : "api.js",
    "instances"  : 4,
    "exec_mode"  : "cluster_mode",
    "error_file" : "./examples/child-err.log",
    "out_file"   : "./examples/child-out.log",
    "pid_file"   : "./examples/child.pid"
  }]
}

日志管理

实时日志管理

$ pm2 logs
$ pm2 logs big-api

Flush清除日志

$ pm2 flush # Clear all the logs

Reloading-all-Logs 重载全部日志

$ pm2 reloadLogs

Log-Configuration 日志配置

$ pm2 start echo.js --merge-logs --log-date-format="YYYY-MM-DD HH:mm Z"

Options:

--merge-logs                 do not postfix log file with process id
--log-date-format <format>   prefix logs with formated timestamp
-l --log [path]              specify entire log file (error and out are both included)
-o --output <path>           specify out log file
-e --error <path>            specify error log file

JSON方式配置

{
  "script"          : "echo.js",
  "error_file"        : "err.log",
  "out_file"        : "out.log",
  "merge_logs"      : true,
  "log_date_format" : "YYYY-MM-DD HH:mm Z"
}

logrotate 日志回滚

$ pm2 install pm2-logrotate
$ sudo pm2 logrotate -u user

Monitoring 管理

命令行

$pm2 monit 

跨服务器管理

你只需要到keymetrics注册个帐号,然后在你的服务器上

$ pm2 link xsdx0lk95zsex7q h7zesfwxsd9xgw3 [machine name]

最大内存自动重启

$ pm2 start big-array.js --max-memory-restart 20M

JSON

{
  "name"   : "max_mem",
  "script" : "big-array.js",
  "max_memory_restart" : "20M"
}

多进程自动均衡负载

Node是单进程的,不能充分利用多核CPU的优势,使用PM2即可解决

# Start the maximum processes depending on available CPUs
$ pm2 start app.js -i 0

# Start the maximum processes -1 depending on available CPUs
$ pm2 start app.js -i -1

# Start 3 processes
$ pm2 start app.js -i 3

热重载

省去不用手动杀死node进程和启动

$ pm2 reload api

Deployment workflow 开发工作流

PM2嵌入简单且强大的部署系统,可以实现多主机,本地化,自动部署

非ROOT用户监听80端口

$ sudo apt-get install authbind
$ sudo touch /etc/authbind/byport/80
$ sudo chown %user% /etc/authbind/byport/80
$ sudo chmod 755 /etc/authbind/byport/80
$ authbind --deep pm2 update
你的欣赏是我最大的动力

Yanxiong Huang

My name is Yanxiong Huang. graduated from Nanyang middle school.Love Linux,familiar with Node.js,Docker,Serverless... and more Web technology.Contact Me:QQ 31356617;Email:huangaynxiong2013@gmail.com

guangzhou,china http://www.myfreax.com

乐在分享