introduce

PM2 is a process manager for Node applications with load balancing function. PM2 can utilize all cpus on the server, keep the process alive forever, and deploy and manage multiple Node projects with zero-second overloads. PM2 is the perfect management tool for online Node deployment

Basic instructions

NPM install Pm2 -g: global installation. Pm2 start app.js: Starts the service. The entry file is app.js. Pm2 start app.js -i [n] --name [name] : Starts N processes. The name is name. NPM restart [name or ID] : restarts the service. NPM Reload [name or ID] : has the same function as Rastart, but can achieve 0s seamless connection; If you have experience with nginx, compare the nginx reload directive. Pm2 start app.js --max_memory_restart 1024M: Automatically restarts when the memory capacity exceeds 1024M. If the project has a tricky memory leak problem, this is a compromise. Pm2 MONIT: Monitors services.Copy the code

View the number of service processes

As for how many processes to start, you can determine by the number of kernels on the server, and how many kernels to start several services. The instructions are as follows:

  Check the number of physical cpus
  cat /proc/cpuinfo| grep "physical id" | sort| uniq | wc -l
  # Check the number of cores per physical CPU
  cat /proc/cpuinfo| grep "cpu cores"| uniq
  # check the number of logical cpus
  cat /proc/cpuinfo| grep "processor"| wc -l
Copy the code

Of course you can start multiple ports, one port for each service, and then you need NignX for load balancing.

Fork and Cluster startup modes

In the development environment, the startup mode is fork, while in the production environment, the startup mode is cluster

pm2 start app.js --name m --watch
Copy the code

Suggestion: This is suitable for development, can save a lot of time, production environment is best not to use

1. Cluster is a derivative of fork. Cluster supports all features of cluster.

2. Fork does not support socket address port multiplexing, whereas cluster does. Because only the Cluster module of a node supports the socket option SO_REUSEADDR;

Fork cannot start multiple instance processes. Cluster can start multiple instances. Node child_process.fork can start multiple processes, but why not? As far as I am concerned, Node mainly provides network services. In this case, the cluster mode can be used to implement address and port reuse when starting multiple instances. However, fork mode does not support address and port reuse. However, for resident task scripts, network services do not need to be provided. In this case, multi-process startup can be realized and the task processing efficiency is also improved. The above requirements can be realized in two ways: one is to configure app0, APP1, and app2 to start multiple processes; the other is to call child_process.fork multi-process programming by the application instance itself.

Fork mode can be applied to other languages such as PHP, Python, Perl, Ruby, bash, coffee, whereas Cluster can only be applied to Node;

Fork does not support scheduled restart, whereas cluster does. Scheduled restart is the cron_restart configuration item in the configuration.

The monitor pm2

Pm2 can be monitored in two ways:

Cli Monitoring

Pm2 Monit is specially used to monitor the command, monitoring items including CPU and memory, shortcomings of monit display content is too rough, not detailed

Pm2 list Displays all pM2 management items

If more detailed monitoring is required, the CLI can generally implement it.

Disadvantages of this monitoring method:

1. It is not intuitive, so you need to execute commands and analyze the results by yourself;

2. It is not convenient for the application monitoring and management of multiple servers;

Log problem

The log system is usually a necessary auxiliary function for any application. Pm2 files are stored in $HOME/. Pm2 / by default. Pm2 logs are classified into two types:

$HOME/. Pm2 /pm2.

Pm2 managed application logs are stored in $HOME/. Pm2 /logs/. Standard error logs are stored in ${APP_NAME}_out.log and standard error logs are stored in ${APP_NAME}_error.log.

The reason why logging is described separately here is that if the program is not developed carefully, in order to debug the program, the application generates a large amount of standard output, so that the server itself records a large number of logs, resulting in the service disk load problem. Generally speaking, PM2 managed applications have their own logging system, so for this unnecessary output you need to disable logging and redirect to /dev/null.

Similarly, crontab logs itself and the output of the applications it manages. The application script output must be redirected to /dev/null, because the output is sent to the user as an email, stored in an email file, which can produce unintended results or cause the script not to be executed at all.

Advanced usage

Pm2 supports configuration file startup:

Pm2 Pm2: generates the configuration file file. json

Pm2 startOrRestart /file/path/ m2. Json: Starts the service using the configuration file

Here is what the m2. Json looks like at development time

{/ * * * Application configuration section * http://pm2.keymetrics.io/docs/usage/application-declaration/ * multiple services, */ apps: [// First application {"name": "alumni2.0"."max_memory_restart": "300M"."cwd": ". /"."script": "./app.js"."log_date_format": "YYYY-MM-DD HH:mm Z"."error_file": "./log/app-err.log"."out_file": "./log/app-out.log"."pid_file": "./log/node.pid"."instances": 6,
          "min_uptime": "60s"."max_restarts": 30."watch": false}}]Copy the code

Six service processes were started in cluster mode. If the service occupies more than 300M memory, the system automatically restarts.

Configuration items

Name Application process name. Script Start script path; CWD specifies the path to start the CWD application. Run in/home/polo/directory/data/release/node/index, js, the script for the/data/release/node/index, js, CWD for/home/polo /; Args parameters passed to the script; Interpreter Specifies the script interpreter; Interpreter_args A parameter passed to the interpreter; Instances Number of started application instances. This parameter is valid only in cluster mode, and the default value is fork. Exec_mode Specifies the application startup mode, including fork and cluster. Watch monitors the restart. When this function is enabled, the changed applications in folders or subfolders will restart automatically. Ignore_watch Ignores listening folders and supports regular expressions. Max_memory_restart Specifies the maximum memory capacity that can be automatically restarted. Env environment variables of type object, such as {"NODE_ENV":"production"."ID": "42"}; Log_date_format Specifies the log date format, for example, YYYY-MM-DD HH: MM :ss. Error_file records the standard error stream,$HOME/.pm2/logs/ xxxerr.log), code errors can be found in this file; Out_file records the standard output stream,$HOME/.pm2/logs/ xxxout. log). If a large number of standard outputs are printed, pM2 logs are too large. Min_uptime An application running less than the specified time is considered to be abnormally started. Max_restarts maximum number of restarts for an exception, that is, the restarts for the restarts for the restarts for the min_uptime running time. Autorestart defaults totrue, automatically restart in case of exception; Cron_restart Crontab time to restart applications. Currently, only the cluster mode is supported. The force of the defaultfalseIf thetrue, you can start a script repeatedly. Pm2 does not recommend this; Restart_delay Delays the restart time when an abnormal restart occurs.Copy the code

Suggestions for stable operation

PM2 is a very good Node process management tool, it has rich features: it can make full use of multi-core CPU and load balancing, can help the application automatically restart after a crash, the specified time (cluster model) and exceed the maximum memory limit.

Here are my suggestions to ensure the stable running of resident application processes:

1, timed restart, the application process running for a long time may always produce some unexpected problems, timing can avoid some unpredictable situations;

2, maximum memory limit, according to the observation to set a reasonable memory limit, to ensure the abnormal operation of the application;

3. Reasonable MIN_uptime. Min_uptime is the minimum duration for normal startup of an application, beyond which it is judged as abnormal startup;

4. Set the abnormal restart delay restart_delay. If the application stops due to abnormal conditions, set the abnormal restart delay to prevent the application from restarting too many times due to unpredictable conditions.

5. Set the number of abnormal restarts. If the number of abnormal restarts is exceeded, the environment is in an uncontrollable state for a long time and the server is abnormal. At this point, you can stop trying, issue error warning notifications, and so on.

The use of PM2 is primarily for resident scripts.

References:

Pm2 website

pm2 github