


Let's talk in depth about how to use the Node process management tool-pm2
How to use the Node process management tool-pm2. The following article will talk about how to use the Node process management tool-pm2. I hope it will be helpful to you!
What is pm2
pm2 is a daemon process management tool that can help you protect and manage your applications. Usually pm2 is used for management when the service goes online. There are actually many things that pm2 can do, such as monitoring file changes and automatically restarting, unified management of multiple processes, built-in load balancing, logging system, etc. Let us take a look at how to use pm2
pm2 Basic commands
First we create a simple node service, create a new folder and executenpm init
, then install pm2
npm i pm2 -g
Create new index.js and index2.js, Write two simple http services, and then use pm2 to manage them. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
//index.js let http = require("http"); let server = http.createServer(); server.on("request", function (req, res) { console.log("------------------enter"); res.write("hello juejin"); res.end(); }); server.listen(3000, function () { console.log(`服务器启动成功,通过http://localhost:3000/进行访问`); });
//index2.js let http = require("http"); let server = http.createServer(); server.on("request", function (req, res) { console.log("------------------enter2"); res.write("hello juejin2"); res.end(); }); server.listen(3001, function () { console.log(`服务器启动成功,通过http://localhost:3001/进行访问`); });
Next we will use the first command of pm2: pm2 start index. js
and pm2 start index2.js
Start these two programs respectively
Of course, if you want to specify the process name, you can do this: pm2 start -n test index.js
, if you want to monitor file changes, you can add --watch
and so on
Visit http://localhost:3000/
Execute pm2 log
You can see the log we printed
pm2 There are many more commands, here are a few
- Stop 1/multiple/all programs
pm2 stop id/id1 id2 id3/all
- Kill Dead 1/multiple/all programs
pm2 delete id/id1 id2 id3/all
- Restart 1/multiple/all programs
pm2 restart id/id1 id2 id3/ all
- Start and view the log
pm2 start api.js --attach
- List the application
pm2 list
- View monitoring panel
pm2 monit
- View program data
pm2 show [id]
Load balancing
We all know that NodeJS is an asynchronous single-threaded language. If it is deployed directly to the server without any processing, then it can only use one thread of the server, which is a huge waste of performance.
Using pm2 only requires one command to allow our program to make full use of the server's CPU. Take index.js as an example: pm2 start index -i max
, for example, my computer is 10 If the core is 20 threads, it will open 20 threads
#Of course, if you want to specify how many threads you want, you can directly change max to the number of threads you want to openpm2 start index -i 3
Configuration file
We all used the command line to manage the above examples, which is actually quite inconvenient. Fortunately, pm2 provides the form of configuration files.
We directly use the command pm2 init simple
to generate a simple configuration file ecosystem.config.js
, modify it to point to our two services
module.exports = { apps: [ { name: "index", script: "./index.js", }, { name: "index2", script: "./index2.js", }, ], };
Then we kill all the original processes and execute pm2 start ecosystem.config.js
. Similarly, our two services are started
The following are some configuration itemsecosystem.config.js
module.exports = { apps: [ { name: "index", //name script: "./index.js", //相对于pm2 start 的相对路径 cwd: "", //要启动的应用程序的目录 instances: 2, //要启动实例的数量,就是上面提到的负载 watch: true, //是否启动监听 env: { NODE_ENV: "development" }, // 将出现在您的应用程序中的 env 变量 env_xxx: { NODE_ENV: "xxx", //使用pm2注入xxx变量进行切换 }, log_date_format: "YYYY-MM-DD HH:mm Z", //日志时间格式 error_file: "./log/index-error.log", //错误文件路径 out_file: "./log/index-out.log", //输出日志文件路径 max_restarts: 10, //最大重启数 restart_delay: 4000, //重启延迟时间ms autorestart: true, //是否自动重启 cron_restart: "", //定时重启 使用cron表达式 }, { name: "index2", script: "./index2.js", }, ], };
Log
The log is very important for back-end troubleshooting, pm2 automatically With log function, for example, we configured the log-related parameters in the above configuration file
log_date_format: "YYYY-MM-DD HH:mm Z", //日志时间格式 error_file: "./log/index-error.log", //错误文件路径 out_file: "./log/index-out.log", //输出日志文件路径
When we start the project, the log will be recorded under the log
The logging function that comes with pm2 does not support log splitting. As time goes by, the log files will become larger and larger, which will not only affect performance, but also be very troublesome to troubleshoot later, so we need to split the logs. The log splitting operation is very simple. You only need to install the pm2-logrotate
plug-in. Note that here is pm2 install
pm2 install pm2-logrotate
and then execute pm2 conf to see the relevant configuration
Explain the relevant meaning
Compress:是否通过 gzip 压缩日志
max_size:单个日志文件的大小
retain:保留的日志文件个数
dateFormat:日志文件名中的日期格式,默认是 YYYY-MM-DD_HH-mm-ss
rotateModule:是否把 pm2 本身的日志也进行分割,
workerInterval:检查文件时间间隔
rotateInterval:设置强制分割,默认值是 0 0 * * *,意思是每天晚上 0 点分割,这里使用的是 corn 表达式,不会的可以搜索一下
如果我们想要配置也很简单,比如修改 max_size
pm2 set pm2-logrotate:max_size 1K
然后我们简单测试一下这个工具,我们先设置每个 log 文件最大 1kb
然后重启我们的项目
pm2 restart ecosystem.config.js
然后就会发现我们的日志被分割了
总结
pm2对于node服务的管理是十分方便的,文中提到的只是其中一部分,如果你想使用pm2管理你的服务的话可以到官网pm2.io/ 进行学习
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of Let's talk in depth about how to use the Node process management tool-pm2. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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



The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

This 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!

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

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".
