An in-depth analysis of Node's process management tool 'pm2”
Apr 03, 2023 pm 06:02 PMThis article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!
PM2 Introduction
PM2 is a node process management tool with a built-in load balancer. You can use it to simplify many tedious tasks of node application management, such as performance monitoring, automatic restart, load balancing, etc., and it is very simple to use. PM2 is perfect when you want your standalone code to utilize all CPUs on all servers and ensure that the process is always alive with 0-second reloads.
PM2 official website address: https://pm2.keymetrics.io/docs/usage/quick-start/
Why do you need pm2?
There are many pain points in Nodejs development at present, because node itself is a single-threaded application. Its characteristic is that all methods are executed serially at once, and node does not have the ability to create alone like Java. A new thread is used to implement asynchronous operations. If it encounters blocking during I/O execution, it will reduce the execution efficiency of the entire application, leading to unfavorable reasons such as high CPU usage. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
Therefore, in this mode, one thread can only process one task. If you want to improve throughput Must pass multithreading. Although single-threading has many benefits, such as avoiding problems such as thread synchronization or deadlock, state synchronization, etc., as applications and computing power requirements are increasing day by day, the biggest disadvantage of single-threading is that it cannot take advantage of multi-core CPUs. advantages to improve operational efficiency. pm2 can deploy your application to all CPUs of the server, effectively solving this problem
Features
Built-in load balancing (using Node cluster cluster module)
Background operation
0 seconds downtime for reloading (no downtime required for maintenance and upgrades) ).
Startup script with Ubuntu and CentOS
Stop unstable processes (avoid infinite loops)
Console detection
Provide HTTP API
Remote control and real-time interface API (Nodejs module, allowing and PM2 process Manager interaction)
Installation
Just use npm to install globally. Of course, you can also use yarn to install
//?npmnpm?install?-g?pm2 ? //?yarnyarn?global?add?pm2
Basic commands
// 啟動命令 pm2 start app.js // 啟動nodeJs應用,進程的默認名稱為文件名app pm2 start app.js--name mynode // 啟動node,并指定進程名稱為mynode pm2 start app.js - i max // 根據有效CPU數目啟動最大進程數目 pm2 start app.js - i 3 // 啟動3個進程 pm2 start app.js--watch // 實時監(jiān)控的方式啟動,app.js文件有變動時,pm2會自動reload pm2 start app.js - x // 用fork模式啟動 app.js 而不是使用 cluster pm2 start app.js - x– - a 23 // 用fork模式啟動 app.js 并且傳遞參數(-a 23) pm2 start app.json // 啟動進程, 在app.json里設置選項 pm2 start app.js - i max– - a 23 // 在 – 之后給 app.js 傳遞參數 pm2 start app.js - i max - e err.log - o out.log // 啟動并生成一個配置文件 // 查看與監(jiān)視進程 pm2 list | pm2 ls // 顯示所有進程; pm2 show 0 | pm2 info 0 // 查看進程id為0的詳細信息 pm2 monit // 進入監(jiān)視頁面,監(jiān)視每個node進程的CPU和內存的使用情況 // 停止、刪除進程 pm2 stop 0 // 停止id為0的進程 pm2 stop all // 停止所有進程 pm2 delete 0 // 刪除id為0的進程 pm2 delete all // 刪除所有進程 // 重啟、重載 pm2 restart 0 // 重啟id為0的進程 pm2 restart all // 重啟所有進程 pm2 reload 0 // 0秒停機重載id為0進程(用于 NETWORKED 進程) pm2 reload all // 重載所有進程 // 日志操作 pm2 logs // 顯示所有進程的日志 pm2 logs 0 // 顯示進程id為0的日志 pm2 flush // 清空所有日志文件 pm2 reloadLogs // 重載所有日志 pm2 startup // 產生init腳本,保持進程活著 // 殺死PM2進程 pm2 kill
pm2 usage
There are two main ways to use pm2: command line and configuration file. Although the method of using the configuration file still requires the use of the command line to start, the main difference between the two is: (1) The command line method requires various configuration parameters to be entered on the command line. (2) The configuration file method places various configuration parameters in the configuration file.
For example: you need to start an application, specify the application name as newApp, and set the entry file path to index.js. Let’s take a look at how to change the application name and entry file path in two ways. Bring in two parameters
【1】Command line method
pm2 start index.js --name newApp
【2】Configuration file method
First we need to create a configuration file (pm2.config.js) , the content is as follows:
// 文件名為 pm2.config.js module.exports = { apps: [{ name: "newApp", // 應用名稱 script: "./index.js" // 入口文件 }] }
Then enter the following content on the command line to indicate that the application will be started with the specified configuration file
pm2 start pm2.config.js
[3] Summary
By comparing the above two In this form, you can see that by using the configuration file, various parameters, environment variables and other contents can be persistently retained in the file, which facilitates batch management of various applications and avoids errors due to forgetting, mistakes, etc. on the command line. The reason is that the startup parameters are uncontrollable.
How to create a configuration file
You can create a Javascript file yourself or use the following command to generate a configuration file. One thing to note is that pm2 It is required that the file name of the configuration file must end with .config.js.
【1】Command generation
pm2 ecosystem
The name of the configuration file generated by the command is economy.config.js, and the format is as follows. You can find that this file exports an object, which has the apps attribute. This It is a list, each item in it corresponds to an application, and the configuration parameters of the corresponding application are set in the object of each sub-item. You can configure multiple applications in the configuration file.
module.exports = { apps : [{ script: 'index.js', watch: '.' }, { script: './service-worker/', watch: ['./service-worker'] }], deploy : { production : { user : 'SSH_USERNAME', host : 'SSH_HOSTMACHINE', ref : 'origin/master', repo : 'GIT_REPOSITORY', path : 'DESTINATION_PATH', 'pre-deploy-local': '', 'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production', 'pre-setup': '' } }};
【2】Create by yourself
If you create a Javascript file by yourself, just create it according to the above format. Note that the file name must end with config.js.
[3] Note
Whether this configuration file is created through a command or created manually, there is no difference between the two as long as it conforms to the syntax. In addition to configuration files in the form of .js, pm2 also supports configuration files in the form of .json and .yml. There is essentially no difference in the forms of these three configuration files, and the parameter names are also exactly the same. The only difference lies in the way the parameters are presented.
案例
我們先創(chuàng)建幾個項目文件用于演示,目錄結構如下,demo1目錄存放的項目project1用命令行方式使用pm2,demo2目錄存放的項目project2和project3用配置文件方式使用pm2, 三個項目都是node.js項目,index.js是非?;A的 Koa 項目入口文件,ecosystem.config.js是配置文件,各自的 node_modules 文件中只安裝了 koa 框架
pm2 ├── demo1 └── project1 | ├── index.js | └── node_modules └── demo2 ├── ecosystem.config.js ├── project2 │ ├── index.js │ └── node_modules └── project3 ├── index.js └── node_modules
入口文件index.js代碼如下,三個項目的port分別為 8001、8002、8003
'use strict' const Koa = require('koa') const app = new Koa() const PORT = 8001 // 三個項目分別為 8001,8002,8003 app.use(ctx => { ctx.body = { NODE_ENV: process.env.NODE_ENV, url: ctx.url, port: PORT, } }) app.listen(PORT)
配置文件ecosystem.config.js 代碼如下
module.exports = { apps: [{ cwd: '../demo2/project2', name: 'project2', script: 'index.js', watch: ['.'] }, cwd: '../demo2/project3', name: 'project3', script: 'index.js', watch: ['.'] }] }
【1】啟動應用
命令行方式:pm2 start xxx.js
配置文件方式:pm2 start || pm2 start ecosystem.config.js
我們使用命令行方式啟動project1應用,進入到project文件目錄,運行pm2 start index.js命令,我們沒有在命令中設定任何參數,pm2 會自動按照默認參數值進行執(zhí)行。例如自動將入口文件的文件名index作為應用名稱。幾乎每一次命令執(zhí)行完成后,pm2 都會顯示一個應用列表(如下圖所示),接著你就可以在網頁中輸入:localhost:8001查看project1項目
我們接著使用配置文件方式啟動project2和project3應用,因為兩個應用的配置在同一個文件,因此我們只需要運行一次配置文件,啟動成功后可在網頁中訪問localhost:8002和localhost:8003
【2】停止應用
使用id停止:pm2 stop
使用name停止:pm2 stop
停止所有應用:pm2 stop all
【3】重啟應用
使用id重啟:pm2 reload
使用name重啟:pm2 reload
重啟所有應用:pm2 reload all
【4】顯示應用列表
pm2 list
pm2 ls
pm2 status
【5】以JSON格式顯示應用列表
pm2 jlist
pm2 prettylist
使用 pm2 jlist 命令,你會發(fā)現輸出的內容很亂,你可以使用 pm2 prettylist 命令來輸出優(yōu)化過的 JSON 格式內容
【6】查看應用信息
pm2 describe id
pm2 describe name
上述的 JSON 格式應用列表,輸出了所有應用的信息,而且信息十分凌亂,我們可以使用 pm2 describe 命令來查看指定應用的信息
【7】實時打印日志
打印日志:pm2 logs
指定日志行數:pm2 logs --lines (指定顯示的日志行數)
清空日志:pm2 flush
對于線上正在運行的應用,有的時候需要打印實時日志來進行調試排查問題,雖然日志會自動添加到日志文件里面,但是總之不太方便。pm2 提供了logs命令,可以直接實時打印日志。
注意:當前命令行頁面使用了該命令后,當前命令行會一直處于監(jiān)聽狀態(tài),你需要再新開一個命令行去敲其他命令
【8】顯示儀表盤
pm2 monit
【9】刪除應用
通過Id刪除:pm2 delete id
通過name刪除:pm2 delete name
刪除所有應用:pm2 delete all
刪除應用幾乎不會造成任何后果,只是在管理列表中刪除了這一項,并不會刪除項目文件
【10】配置參數-應用名稱
--name
在命令行方式中,使用 --name
【11】配置參數-監(jiān)聽目錄
監(jiān)聽目錄:--watch
指定目錄不被監(jiān)聽:--ignore-watch
監(jiān)聽目錄用于當指定監(jiān)聽目錄文件發(fā)生變化時,pm2 將會自動重啟應用
除了指定一個監(jiān)聽目錄外,還可以再繼續(xù)指定某個目錄不被監(jiān)聽,例如上述的例子,指定了project1目錄為監(jiān)聽目錄,然后你把日志文件放在了這個目錄下,比如為 logs 目錄,這個目錄不希望被監(jiān)聽,否則會形成死循環(huán),這時候就需要用到另一個參數 --ignore-watch,輸入一下命令
pm2 start 0 --watch --ignore-watch './logs'
【12】配置參數-最大內存數
--max-memory-restart xxx(K|M|G)
設置最大內存數,當應用運行時占用的內存超出該數值后,應用將自動重啟。命令行方式通過 --max-memory-restart 參數設定應用運行最大內存,后續(xù)跟上數值和單位,單位只能是 K,M,G 三個值,分別表示 KB,MB,GB 。
【13】配置參數-日志存放路徑
--log
日志默認會放置在 $HOME/.pm2/logs/ 目錄下,使用 --log
pm2 start index.js --log ./logs/mylog.log
更多node相關知識,請訪問:nodejs 教程!
The above is the detailed content of An in-depth analysis of Node's process management tool 'pm2”. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices
