Home  >  Article  >  Web Front-end  >  Let’s talk in depth about how to use the Node process management tool-pm2

Let’s talk in depth about how to use the Node process management tool-pm2

青灯夜游
青灯夜游forward
2023-04-19 18:59:121700browse

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!

Let’s talk in depth about how to use the Node process management tool-pm2

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

Let’s talk in depth about how to use the Node process management tool-pm2

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/

Let’s talk in depth about how to use the Node process management tool-pm2

Execute pm2 logYou can see the log we printed

Let’s talk in depth about how to use the Node process management tool-pm2

pm2 There are many more commands, here are a few

  • Stop 1/multiple/all programspm2 stop id/id1 id2 id3/all
  • Kill Dead 1/multiple/all programspm2 delete id/id1 id2 id3/all
  • Restart 1/multiple/all programspm2 restart id/id1 id2 id3/ all
  • Start and view the logpm2 start api.js --attach
  • List the applicationpm2 list
  • View monitoring panelpm2 monit
  • View program datapm2 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

Let’s talk in depth about how to use the Node process management tool-pm2

#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

Let’s talk in depth about how to use the Node process management tool-pm2

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

Let’s talk in depth about how to use the Node process management tool-pm2

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

Let’s talk in depth about how to use the Node process management tool-pm2

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

Let’s talk in depth about how to use the Node process management tool-pm2

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

然后就会发现我们的日志被分割了

Let’s talk in depth about how to use the Node process management tool-pm2

总结

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete