1. What is PM2
- It is a process management tool for Nodejs that can be used in production environments, and it has a built-in load balancing. It not only ensures that the service will not be interrupted and is always online, but also provides a 0-second reload function, but also has a series of other process management and monitoring functions. And it's very simple to use.
- Well, the best use is to monitor the running status of node programs in our production environment, so that it can give us a working state day by day.
-
pm2 official document
2. Use pm2
- In the primitive society, we developed node server programs in general:
- Write a node program and run node; or write script to run it with npm; open browser access;
- It seems that the content needs to be modified, but the browser does not display the modified content? ->node ->Run again;
- The browser suddenly cannot access the service, and it seems something went wrong? Restart ->node -> run again;
- Oh, I opened many console windows, but it was closed accidentally, and the service could not be accessed again. Continue to open the console ->node -> run again;
- Very collapsed! It seems that there is a tool nodemon; install it using nodemon; wow, it can automatically listen to file modification changes and restart automatically, but closing the console service will still be destroyed.
- Through this very commonly used scenario, we learned that to avoid these troubles, a server needs at least: background operation and automatic restart, these two capabilities.
- Let’s take a look at the abilities you can have using pm2:
- Log management; two types of logs, pm2 system log and managed process log, will record the process console output to the log by default;
- Load Balancing: PM2 can extend your application by creating multiple child processes that share the same server port. Doing so also allows the application to be restarted with zero-second downtime.
- Terminal Monitoring: You can monitor the application in the terminal and check the application health status (CPU usage, memory used, requests/minutes, etc.).
- SSH deployment: Automatic deployment, avoid sshing one by one in all servers.
- Static service: Supports static server function
- Supports development and debugging mode, non-background operation, pm2-dev start <appName>;
- . . . . . Too powerful!
Common pm2 commands
Start the service pm2 start <script_file|config_file> [options] Start the specified application
pm2 start //Start the applicationpm2 start --name app //Start the application and set the namepm2 start // Script start pm2 start --watch //Supervising mode starts, and automatically restarts when the file changes. //max means PM2 will automatically detect the number of available CPUs and run as many processes as possible//Max can be customized. If it is a 4-core CPU, setting it to 2 will take up 2pm2 start -i max //Enable cluster mode (automatic load balancing) pm2-dev start ... // Development mode starts, that is, background operation is not enabled
View the startup list pm2 list
Show application details pm2 show <appName> [options] Show specified application details
pm2 show [Name] //View by namepm2 show [ID] //according toidCheck
Stop the specified application pm2 stop <appName> [options] Stop the specified application
pm2 stop all //Stop all applicationspm2 stop [AppName] //Stop the specified application according to the application namepm2 stop [ID] //According to the applicationidStop the specified application
Restart the application pm2 reload|restart <appName> [options] Restart the specified application
pm2 restart //Kill and restart all processes at the same time. The service is unavailable in a short period of time. Use it with caution when generating an environment.pm2 reload //Restart all processes, restart in 0 seconds, always keep at least one process runningpm2 gracefulReload all //Reload all applications in cluster mode
Start the static server pm2 serve ./dist 8080. Use directory dist as the root directory of the static server, and the port is 8080.
Delete the application pm2 delete <appName> [options] Delete the specified application; if the application configuration behavior is modified, the application needs to be deleted first and then restarted before it will take effect, such as modifying the script entry file;
pm2 delete all //Close and delete the applicationpm2 delete [AppName] //Close and delete the application according to the application namepm2 delete [ID] //According to the applicationIDClose and delete the app
pm2 kill kills all processes managed by pm2;
pm2 logs <appName> View the log of the specified application, that is, standard output and standard errors
pm2 logs //View all application logspm2 logs [Name] //View application log according to the specified application namepm2 logs [ID] //According to the specified applicationIDView application log
pm2 monit Monitors the usage of CPU and memory in each application process;
PM2 configuration method
The command produces the default example configuration file pm2 ecosystem or pm2 init. Running the configuration file by default will be generated.
= { apps: [ { name: 'back-Api', //Application name script: './server/', //Application file location env: { PM2_SERVE_PATH: "./apidoc", // Static service path PM2_SERVE_PORT: 8080, // Static server access port NODE_ENV: 'development' //Start the default mode }, env_production : { NODE_ENV: 'production' //Use production mode pm2 start --env production }, instances:"max", //Distribute the application on all CPU cores, which can be integer or negative instance_var: "INSTANCE_ID", exec_mode: "cluster", watch:[ "server", ], //The listening mode cannot be simply set to true, which can easily lead to infinite restarts, because the log file is changing, so it is necessary to exclude listening to it merge_logs: true, //In the case of cluster, logs can be merged } ], deploy: { production : { user: 'node', //ssh user host: '212.83.163.1', //ssh address ref: 'origin/master', //GIT Remote/Brand repo: 'git@:', //git address path: '/var/www/production', //Server file path "post-deploy": 'npm install && pm2 reload --env production' //Action after deployment } } };
Custom json configuration file such as:; start pm2 start
{ "apps": [{ "name": "app", //name "script": "./", //Program portal "cwd": "./", //Root directory "watch":[ "views" ],//Catalogues that need to be monitored "error_file":"./logs/",//Error output log "out_file":"./logs/", //log "log_date_format":"YYYY-MM-DD HH:mm Z" //Date format }] }
Analysis of common configuration items for pm2
1. apps:json structure, apps is an array, and each array member corresponds to an application running in pm2
2. name: application name "app"
3. cwd: the directory "./" where the application is located
4. script: The script path of the application "./"
5. log_date_format: log file name output date format "YYYY-MM-DD HH:mm Z"
6. error_file: Customize the application's error log file "./logs/",
7. out_file: Custom application log file "./logs/"
8. instances: The number of application startup instances is only valid in cluster mode. The default is fork; or max
9. min_uptime: minimum running time, the setting here is 60s that is, if the application exits within 60s, pm2 will consider the program to exit abnormally. At this time, the restart of max_restarts is triggered.
10. max_restarts: Set the number of times the application exits and restarts abnormally, default 15 times (counting from 0)
11. cron_restart: Start regularly to solve problems that can be solved by restarting
12. watch: Whether to enable monitoring mode, the default is false. If set to true, pm2 will be automatically reloaded when the application changes. You can also set the files you want to monitor here.
13. "ignore_watch": [
"node_modules",
"logs"
],
13. merge_logs:// set append log instead of creating new log
14. exec_interpreter: The script type of the application, the shell used here is nodejs by default
15. exec_mode: application startup mode, the cluster_mode is set here, and the default is fork
16. autorestart: Enable/disable the application to automatically restart when it crashes or exits. The default is true. It will automatically restart if an exception occurs.
17. vizion: enable/disable vizion feature (version control)
18. "args": "", // Parameters passed to the script
19. env: {
PM2_SERVE_PATH: "./apidoc", //static service path
PM2_SERVE_PORT: 8080, // Static server access port
NODE_ENV: 'development' //Start the default mode
},
20. env_production : {
NODE_ENV: 'production' //Use production mode pm2 start --env production
},
pm2 and log4js handle logs
1. When pm2 is started, it is usually found that log4js cannot record log information;
2. Solution: Install pm2-intercom interprocess communication module of pm2
3. Add the following command to the log4js configuration file:
pm2: true, pm2InstanceVar: 'INSTANCE_ID'
4. Add "instance_var": "INSTANCE_ID" in the pm2 configuration file, // Add this line field
5. It is found that if the cluster mode "exec_mode": "cluster" is not set, it will not be recorded;
other
Log4js log configuration usage detailsKoa log middleware packaging development (log4js)
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.