進階 PM2

PM2 大大簡化了 Node 任務操做,除了簡單的應用外,咱們還能夠作一些有趣的事情。本節咱們來探討一下 PM2 的平滑啓動以及數據監控。php

若是你還不瞭解 PM2,能夠先看看 PM2 初體驗,或者查看 PM2 用法簡介node

1、PM2 兩種啓動方式

1.cluster_mode:用 cluster 來作負載均衡,咱們不須要作任何代碼的改動。 2.fork_mode:用 fork 模式啓動(默認),這能夠容許咱們經過改變 exec_interpreter 參數,啓動 php 或者 python 服務。python

Node.js 給咱們提供了 cluster 模塊,它能夠生成多個工做線程來共享同一個 TCP 鏈接。git

2、實時擴展集羣

任什麼時候候,若是咱們須要增長工做線程的數量,能夠經過 pm2 scale <app name> <n> 來對集羣進行擴展。參數 <n> 指定工做線程的數量,被用來增長或減小集羣數。github

補充:能夠經過 pm2 scale app +3 的方式來指定要增長多少工做線程。web

PM2reload <app name> 功能將依次重啓全部的工做線程。每個線程會等待在新的線程建立以後纔會被終止掉,所以,當你在產品環境部署新的代碼時,Server 會不間斷地一直保持運行。shell

3、平滑重啓

1.fork 模式npm

{
   "apps" : [{
     "name"         : "pc",
     "script"       : "jartto-server.js",
     "kill_timeout" : 3000,
     "instances": 2,
     "log_date_format": "YY-MM-DD HH:mm:ss Z"
  }]
}
const httpServer = server.listen(port, error => {
   if (error) {
       throw error;
  }
   process.send('ready');
});
process.on('SIGINT', () => {
   httpServer.close(error => {
       process.exit(error ? 1 : 0);
  });
});
複製代碼

2.cluster 在集羣模式下,有一個默認系統可在應用程序接受鏈接時將每一個集羣設置爲就緒。還有一個超時,默認爲 3000 毫秒,咱們可使用 ecosystem 文件中的 listen_timeout 屬性進行設置。json

生成 ecosystem.config.jsapi

pm2 ecosystem
複製代碼

輸出日誌:

[PM2] Spawning PM2 daemon with pm2_home=/Users/jartto/.pm2
[PM2] PM2 Successfully daemonized
File /Users/jartto/Documents/project/ecosystem.config.js generated
複製代碼

簡單示例:

module.exports = {
  apps: [{}, {}], // 存放每個進程的配置信息
  deploy: {} // 包含部署配置的對象
}
複製代碼

以後,就能夠經過 startOrRestart 來啓動了:

"scripts": {
    "start": "cross-env PATH_TYPE=test pm2 startOrRestart ecosystem.config.js --only jartto-test --env test",
}
複製代碼

關於 appsdeploy 下面咱們來細緻聊一聊。

4、apps 部分

上面 ecosystem.config.js 會生成一個簡單的模版,爲了更好的掌握,咱們來看看更全的一些配置:

module.exports = {
    apps : [{
        name: 'Jartto-test', // 進程名稱
        script: './node_modules/nuxt-start/bin/nuxt-start.js', // 啓動腳本地址
        args: '-p 8888 -H 0.0.0.0', // 啓動的配置
        cwd: 
        instances: 4,
        autorestart: true,
        watch: false,
        max_restarts: 5,
        max_memory_restart: '1G',
        env: {
            NODE_ENV: 'development'
        },
        env_production: {
            NODE_ENV: 'production'
        }
    }],
    deploy : {
        production : {
            user : 'node',
            host : '212.83.163.1',
            ref : 'origin/master',
            repo : 'git@github.com:repo.git',
            path : '/var/www/production',
            post-deploy : 'npm install && pm2 reload ecosystem.config.js --env production'
        }
    }
};
複製代碼

參數意義:

  • apps:json 結構,apps 是一個數組,每個數組成員就是對應一個pm2中運行的應用
  • name:應用程序的名稱
  • cwd:應用程序所在的目錄
  • script:應用程序的腳本路徑
  • exec_interpreter:應用程序的腳本類型,這裏使用的 shell,默認是 nodejs
  • min_uptime:最小運行時間,這裏設置的是 60s 即若是應用程序在 60s 內退出,pm2 會認爲程序異常退出,此時觸發重啓 max_restarts 設置數量
  • max_restarts:設置應用程序異常退出重啓的次數,默認 15 次(從0開始計數)
  • exec_mode:應用程序啓動模式,這裏設置的是 cluster_mode(集羣),默認是 fork
  • error_file:自定義應用程序的錯誤日誌文件
  • out_file:自定義應用程序日誌文件
  • pid_file:自定義應用程序的 pid 文件
  • watch:是否啓用監控模式,默認是 false。若是設置成 true,當應用程序變更時,pm2 會自動重載。這裏也能夠設置你要監控的文件。

5、deploy 部分

1.生成公鑰

ssh-keygen -t rsa
ssh-copy-id jartto@server.com
複製代碼

補充說明一下: ssh-copy-id 命令能夠把本地主機的公鑰複製到遠程主機的 authorized_keys 文件上,實現免密碼登錄。

2.配置 ecosystem 文件

module.exports = {
  apps: [{
    name: "app",
    script: "app.js"
  }],
  deploy: {
    // "production" is the environment name
    production: {
      // SSH key path, default to $HOME/.ssh
      key: "/path/to/some.pem",
      // SSH user
      user: "Jartto",
      // SSH host
      host: ["192.168.0.13"],
      // 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/master",
      // GIT remote
      repo: "git@github.com:jartto/repository.git",
      // path in the server
      path: "/var/www/jartto-repository",
      // Pre-setup command or path to a script on your local machine
      'pre-setup': "apt-get 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-local': "echo 'This is a local executed command'",
      // post-deploy action
      'post-deploy': "npm install",
    },
  }
}
複製代碼

命令很簡單,都有註釋,這裏就不贅述了。

3.是時候啓動了

# Setup deployment at remote location
pm2 deploy production setup

# 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"
複製代碼

更多配置項:

pm2 deploy <configuration_file> <environment> <command>
  Commands:
    setup                run remote setup commands
    update               update deploy to the latest release
    revert [n]           revert to [n]th last deployment or 1
    curr[ent]            output current release commit
    prev[ious]           output previous release commit
    exec|run <cmd>       execute the given <cmd>
    list                 list previous deploy commits
    [ref]                deploy to [ref], the "ref" setting, or latest tag
複製代碼

瞭解更多,請參考官方文檔

6、環境變量

pm2 經過在配置文件中經過 env_xx 來聲明不一樣環境的配置,而後在啓動應用時,經過 --env 參數指定運行的環境。一個簡單的示例可能以下:

"env": {
    "NODE_ENV": "production",
    "REMOTE_ADDR": "http://www.jartto.wang/"
  },
  "env_dev": {
    "NODE_ENV": "development",
    "REMOTE_ADDR": "http://dev.jartto.wang/"
  },
  "env_test": {
    "NODE_ENV": "test",
    "REMOTE_ADDR": "http://test.jartto.wang/"
  }
複製代碼

7、負載均衡

PM2 提供了強大的負載能力,咱們能夠經過以下命令來開啓:

pm2 start app.js -i 3 # 開啓三個進程
pm2 start app.js -i max # 根據機器CPU核數,開啓對應數目的進程
複製代碼

8、數據監控

PM2 提供了一個數據監控命令:pm2 monit,執行命令後,大概界面以下:

monit

看起來不錯,惋惜並不實用。你們可能發現了,在實際場景下,咱們線上環境會有 N 臺服務器,你會一臺臺上去看監控數據嗎?

顯然,咱們碰到了另外一種場景,那麼如何才能統一監控呢?

不要着急,PM2 爲咱們提供了另一種方式,經過在 Server 端運行命令:pm2 web,咱們能夠在該機器啓動一個監聽服務:

web

以後,你能夠經過 主機 IP:9615 來獲取數據,以下圖:

api

獲取數據能夠經過客戶端輪詢,或者是服務端 Socket 推送,It's up to you!

最後,咱們來看看數據格式:

data

有了數據,那麼可視化豈不是小菜一碟,咱們就能夠在本地實時監控以下數據:
1.服務器內存狀況;
2.CPU 使用狀況;
3.各個站點服務狀況,是否正常運轉,是否報錯,是否頻繁重啓等;
4.服務器平均負載;
...

9、重置狀態

既然經過 PM2 來監控數據了,那麼咱們確定但願每次的數據是準確的,因此這時候就可使用:

pm2 reset jartto-test
複製代碼

來重置服務狀態。

10、最終效果

有了數據,可視化就很是容易了,咱們來看一個簡單的示例:

show

固然,你能夠作的更好,快發揮你創造性,作一些有趣的事情吧!

相關文章
相關標籤/搜索