[nodejs] pm2 : nodejs 的進程管理工具

0 pm2 概述

0.1 序

0.2 pm2 簡述

  • PM2 是一款非常優秀的 Node 進程管理工具,它有着豐富的特性:能夠充分利用多核 CPU且能夠負載均衡、能夠幫助應用在崩潰後、指定時間(cluster model)和超出最大內存限制等情況下實現自動重啓
  • PM2 是開源的基於 Nodejs應用進程管理器,包括守護進程,監控,日誌的一整套完整的功能

PM2 是一個帶有負載均衡功能的 Node 應用進程管理器

0.3 pm2的主要特性

  • 內建負載均衡(使用 Node cluster 集羣模塊)
  • 後臺運行
  • 0 秒停機重載,我理解大概意思是維護升級的時候不需要停機.
  • 具有 Ubuntu 和 CentOS 的啓動腳本
  • 停止不穩定的進程(避免無限循環)
  • 控制檯檢測
  • 提供 HTTP API
  • 遠程控制和實時的接口 API(Nodejs 模塊,允許和 PM2 進程管理器交互)

1 pm2的安裝

Step1 安裝nodejs/npm

  • 在使用pm2之前,我們還需要安裝nodejs/npm,這是前提

下載nodejs:

如何安裝nodejs?

Step2 基於npm安裝pm2

  • 安裝pm2
# 全局安裝 pm2
npm install pm2 -g

npm install 
  • 查看版本
pm2 -v
或 pm2 --version
  • 補充:基於yarn安裝pm2
yarn global add pm2

2 pm2的常用命令

啓動/停止/重啓/重置/重載/刪除

  • 啓動
# 啓動進程/應用 
pm2 start app.js
或 pm2 start bin/www 
或 pm2 start app.js --name my-app
或 pm2 start app.js -i 4 
    # 根據CPU核數啓動進程個數。
    # cluster mode 模式啓動4個app.js的應用實例,4個應用程序會自動進行負載均衡
或 pm2 start app.js --watch 
    # 實時監控app.js的方式啓動。當app.js文件有變動時,pm2會自動reload


# 重命名進程/應用 
pm2 start app.js --name wb123

# 添加進程/應用 
pm2 start bin/www --watch
  • 停止
# 結束進程/應用 
pm2 stop www

# 結束所有進程/應用 
pm2 stop all
# 停止PM2列表中進程爲0的進程
pm2 stop 0
  • 重載/重啓
# 重載PM2列表中cluster mode下所有的進程
pm2 reload all 
# 重載PM2列表中進程爲0的進程
pm2 reload 0

# 重新啓動所有進程/應用 
pm2 restart all
# 重新啓動指定的進程/應用 
pm2 restart www
pm2 restart 0

# 重置重啓
// Graceful reload all apps in cluster mode
pm2 gracefulReload all 
pm2 reset [app-name]
  • 刪除應用/進程
# 刪除所有進程/應用 
pm2 delete all
# 刪除指定的進程/應用 
pm2 delete www
pm2 delete 0

查看/監控/日誌

  • 查看/列出應用/進程
# 列出所有進程/應用 
pm2 list

# 顯示應用程序的所有信息
pm2 show [app-name] 
或 pm2 show 0
# 查看進程詳細信息,0爲PM2進程id
pm2 info 0 

# 查看某個進程/應用具體情況 
pm2 describe www
  • 監控應用/進程
# 查看進程/應用的資源消耗情況 (顯示每個應用程序的CPU和內存佔用情況)
pm2 monit
  • 日誌操作
pm2 logs # 顯示所有應用程序的日誌
pm2 logs [app-name] # 顯示指定應用程序的日誌
    # 例如:若要查看某個進程/應用的日誌 : pm2 logs www

pm2 logs [–raw] #Display all processes logs in streaming
pm2 flush #Empty all log file
pm2 reloadLogs #Reload all logs

系統級/遠程操作/安裝/卸載/其他

  • 系統級命令
pm2 startup # 創建開機自啓動命令
pm2 save # 保存當前應用列表
pm2 resurrect # 重新加載保存的應用列表
pm2 update # Save processes, kill PM2 and restore processes
pm2 generate # Generate a sample json configuration file
  • 遠程操作
pm2 deploy app.json prod setup # Setup “prod” remote server
pm2 deploy app.json prod # Update “prod” remote server
pm2 deploy app.json prod revert 2 # Revert “prod” remote server by 2
  • 安裝/升級/卸載
npm install pm2@lastest -g # 安裝最新的PM2版本
pm2 updatePM2 # 升級pm2
pm2 module:generate [name] # Generate sample module with name [name]
pm2 install pm2-logrotate # Install module (here a log rotation system)
pm2 uninstall pm2-logrotate # Uninstall module
pm2 publish # Increment version, git push and npm publish
  • 其他命令
pm2 start script.sh # 啓動 bash 腳本
pm2 scale api 10 # 把名字叫api的應用擴展到10個實例
pm2 reset [app-name] # 重置重啓數量
  • 更多 、幫助
pm2 --help

3 PM2目錄結構

默認的目錄是:當前用於的HOME目錄下的.pm2目錄(此目錄可以自定義),詳細信息如下:

$HOME/.pm2                   # will contain all PM2 related files
$HOME/.pm2/logs              # will contain all applications logs
$HOME/.pm2/pids              # will contain all applications pids
$HOME/.pm2/pm2.log           # PM2 logs
$HOME/.pm2/pm2.pid           # PM2 pid
$HOME/.pm2/rpc.sock          # Socket file for remote commands
$HOME/.pm2/pub.sock          # Socket file for publishable events
$HOME/.pm2/conf.js           # PM2 Configuration

4 自定義PM2啓動文件

創建一個test.json的示例文件,格式如下:

~]# mkdir -p /opt/htdocs/testapp
~]# cd /opt/htdocs/testapp
testapp]# cat test.json
{
    "apps": [
        {
            "name": "test",
            //"port": "8003", // 啓動端口
            "cwd": "/opt/htdocs/testapp",
            "script": "./test.sh",
            "exec_interpreter": "bash",
            "log_date_format": "YYYY-MM-DD HH:mm Z",
            "error_file": "./test-err.log",
            "out_file": "./test-out.log",
            "pid_file": "./test.pid",
            "instances": 6,
            "min_uptime": "200s",
            "max_restarts": 10,
            "max_memory_restart": "1M",
            "cron_restart": "1 0 * * *",
            "watch": false,
            "merge_logs": true,
            "exec_mode": "fork",
            "autorestart": false,
            "vizion": false
        }
    ]
}

參數說明:

apps:json結構,apps是一個數組,每一個數組成員就是對應一個pm2中運行的應用
name:應用程序名稱
cwd:應用程序所在的目錄
script:應用程序的腳本路徑
log_date_format:配置日誌的輸出格式
error_file:自定義應用程序的錯誤日誌文件六、實例展示
out_file:自定義應用程序日誌文件已上面的test.json爲例
pid_file:自定義應用程序的pid文件
instances:啓動腳本相 默認 nodejs
min_uptime:最小運行時間,這裏設置的是60s即如果應用程序在60s內退出,pm2會認爲程序異常退出,此時觸發重啓max_restarts設置數量
max_restarts:設置應用程序異常退出重啓的次數,默認15次(從0開始計數
cron_restart:定時啓動,解決重啓能解決的問題
watch:是否啓用監控模式,默認是false。如果設置成true,當應用程序變動時,pm2會自動重載。這裏也可以設置你要監控的文件。done
merge_logs:combine_logs的別名
exec_interpreter:應用程序的腳本類型,這裏使用的shell,默認是nodejs
exec_mode:應用程序啓動模式,這裏設置的是cluster_mode(集羣),默認是fork
autorestart:啓用/禁用應用程序崩潰或退出時自動重啓
vizion:啓用/禁用vizion特性(版本控制)

執行如下命令:

testapp]# pm2 start test.json 
[PM2][WARN] You are starting 6 processes in fork_mode without load balancing. To enable it remove -x option.
[PM2][WARN] Applications test not running, starting...
[PM2] cron restart at 1 0 * * *
[PM2] App [test] launched (6 instances)
┌──────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬──────────┬──────┬──────────┐
│ App name │ id │ mode │ pid  │ status │ restart │ uptime │ cpu │ mem      │ user │ watching │
├──────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼──────────┼──────┼──────────┤
│ test     │ 0  │ fork │ 2194 │ online │ 0       │ 0s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 1  │ fork │ 2196 │ online │ 0       │ 0s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 2  │ fork │ 2198 │ online │ 0       │ 0s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 3  │ fork │ 2200 │ online │ 0       │ 0s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 4  │ fork │ 2202 │ online │ 0       │ 0s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 5  │ fork │ 2204 │ online │ 0       │ 0s     │ 0%  │ 1.4 MB   │ root │ disabled │
└──────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴──────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app


[root@bogon testapp]# pm2 list
┌──────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬──────────┬──────┬──────────┐
│ App name │ id │ mode │ pid  │ status │ restart │ uptime │ cpu │ mem      │ user │ watching │
├──────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼──────────┼──────┼──────────┤
│ test     │ 0  │ fork │ 2221 │ online │ 1       │ 5s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 1  │ fork │ 2225 │ online │ 1       │ 5s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 2  │ fork │ 2229 │ online │ 1       │ 5s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 3  │ fork │ 2233 │ online │ 1       │ 5s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 4  │ fork │ 2237 │ online │ 1       │ 4s     │ 0%  │ 1.4 MB   │ root │ disabled │
│ test     │ 5  │ fork │ 2241 │ online │ 1       │ 4s     │ 0%  │ 1.4 MB   │ root │ disabled │
└──────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴──────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app


testapp]# pm2 delete all
[PM2] Applying action deleteProcessId on app [all](ids: 0,1,2,3,4,5)
[PM2] [test](3) ✓
[PM2] [test](1) ✓
[PM2] [test](0) ✓
[PM2] [test](2) ✓
[PM2] [test](4) ✓
[PM2] [test](5) ✓
┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app
[root@bogon testapp]# pm2 list      
┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

Y 擴展:PM2與Docker的對比

  • PM2 是一個Nodejs進程管理工具,而 Docker 是一個容器化平臺。它們在部署方式、優點和用途上有一些差異。

  • PM2 的優點:

  • 簡單易用:PM2 提供了簡單的命令行接口,可以方便地管理應用程序的生命週期,如啓動、停止、重啓等。
  • 進程管理:PM2 可以監控和管理多個進程,並提供日誌管理、負載均衡等功能,從而更好地利用系統資源和保持應用程序的穩定性。
  • 自動重啓:如果應用程序崩潰或發生錯誤,PM2 可以自動重啓它,確保應用程序始終可用。
  • 運行時診斷:PM2 提供了實時監控和診斷工具,可以查看內存使用情況、CPU 使用情況和請求量等關鍵指標,幫助排查問題和性能調優。
  • Docker 的優點:
  • 環境隔離:Docker 使用容器來隔離應用程序及其依賴項,使得在不同環境中運行應用程序更加一致可靠。這意味着你可以在開發、測試和生產環境中使用相同的容器鏡像,避免了環境配置的問題。
  • 輕量級和可移植性:Docker 容器非常輕量級,佔用資源較少。由於容器是獨立的、自包含的單元,可以輕鬆地在不同的主機和平臺上部署和遷移。
  • 版本控制和復現性:Docker 鏡像可以通過 Dockerfile 追蹤和管理,這樣你可以確保應用程序的版本一致性,並能夠簡化部署過程。此外,Docker 鏡像的分層結構可以使鏡像構建更加高效,減少資源消耗。
  • 擴展和集羣:Docker 可以方便地擴展應用程序,通過容器編排工具(如 Docker Compose、Kubernetes)可以輕鬆地進行多容器的管理和擴展。
  • 差異與用途:
  • PM2 更適合傳統的服務器部署方式,適用於管理和監控多個 Node.js 進程,提供進程管理相關功能。
  • Docker 更適合容器化部署,適用於將應用程序及其依賴項打包成容器鏡像,並在不同環境中進行部署、遷移和擴展。
  • 最佳實踐:可基於Docker部署PM2的前端應用

綜上所述,PM2 更注重進程管理和應用程序的穩定性,而 Docker 更注重環境隔離、可移植性和版本控制。
需根據你的需求和部署方式選擇合適的工具。
在某些情況下,也可以結合使用 PM2 和 Docker,例如將使用 PM2 管理的 Node.js 應用程序放置在 Docker 容器中進行部署。

X 參考與推薦文獻

  • 基於docker部署pm2前端應用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章