Nodejs PM2 Configuration Usage Tutorial

Source: Internet
Author: User
Tags json socket

First, Introduction

PM2 is an application process manager with load balancing function, similar to Supervisor,forever.

Second, the installation

Linux binaries Download Address: https://nodejs.org/dist
CD ONEINSTACK/SRC
wget https://nodejs.org/dist/v4.2.4/node-v4.2.4-linux-x64.tar.gz
Tar xzf node-v4.2.4-linux-x64.tar.gz
CP node-v4.2.4-linux-x64/bin/node/usr/local/bin/
Cp-r node-v4.2.4-linux-x64/lib/node_modules/usr/local/lib/
Ln-s/USR/LOCAL/LIB/NODE_MODULES/NPM/BIN/NPM-CLI.JS/USR/LOCAL/BIN/NPM
NPM Install Pm2@latest-g #安装最新版本pm2模块
PS: If your host can not connect to the public network, first find the main installation of the public network to install the PM2, and then copy to the host you want to install. Copy the following directory:
/usr/local/bin/node
/usr/local/lib/node_modules
Then create the related soft connection

Three, PM2 common command

Suppose you have now written a app.js file that needs to be started and you can use PM2 to manage

1. Start

# PM2 Start App.js
# PM2 Start app.js--name my-api #my-api for PM2 process name
# PM2 start App.js-i 0 #根据CPU核数启动进程个数
# PM2 start app.js--watch #实时监控app. js, when app.js file changes, PM2 automatically reload
2. View process
# PM2 List
# PM2 Show 0 or # PM2 info 0 #查看进程详细信息, 0 is PM2 process ID
3. Monitoring
# PM2 Monit
4. Stop
# PM2 Stop All #停止PM2列表中所有的进程
# PM2 Stop 0 #停止PM2列表中进程为0的进程
5. Heavy Duty
# PM2 Reload All #重载PM2列表中所有的进程
# PM2 Reload 0 #重载PM2列表中进程为0的进程
6. Reboot
# PM2 Restart all #重启PM2列表中所有的进程
# PM2 Restart 0 #重启PM2列表中进程为0的进程
7. Delete the PM2 process
# PM2 Delete 0 #删除PM2列表中进程为0的进程
# PM2 Delete all #删除PM2列表中所有的进程
8. Log operation
# PM2 logs [--raw] #Display all processes logs in streaming
# PM2 Flush #Empty All log file
# PM2 Reloadlogs #Reload all logs
9. Upgrade PM2
# NPM Install pm2@lastest-g #安装最新的PM2版本
# PM2 UpdatePM2 #升级pm2
10. More command parameters please see Help
# PM2--help

Iv. PM2 directory structure

The default directory is the. PM2 directory that is currently used in the home directory (this directory can be customized, please refer to: Five, custom startup files), details are as follows:
$HOME/.pm2 #will contain all PM2 related files
$HOME/.pm2/logs #will contain all applications logs
$HOME/.pm2/pids #will contain all applications PIDs
$HOME/.pm2/pm2.log #PM2 Logs
$HOME/.pm2/pm2.pid #PM2 PID
$HOME/.pm2/rpc.sock #Socket file for remote commands
$HOME/.pm2/pub.sock #Socket file for publishable events
$HOME/.pm2/conf.js #PM2 Configuration

V. Custom startup files

Create a Test.json sample file in the following format:
{
"Apps":
{
' Name ': ' Test ',
"CWD": "/data/wwwroot/nodejs",
"Script": "./test.sh",
"Exec_interpreter": "Bash",
"Min_uptime": "60s",
"Max_restarts": 30,
"Exec_mode": "Cluster_mode",
"Error_file": "./test-err.log",
"Out_file": "./test-out.log",
"Pid_file": "./test.pid"
"Watch": false
}
}

Description

Apps:json structure, apps is an array, each array member is corresponding to a PM2 operation of the application
Name: Names of applications
CWD: The directory where the application resides
Script: Scripting path for Applications
Exec_interpreter: The script type of the application, the shell used here, the default is Nodejs
Min_uptime: Minimum run time, set here is 60s that is, if the application exits within 60s, PM2 will assume that the program exits unexpectedly, triggering the restart Max_restarts set number
Max_restarts: Sets the number of times the application abnormally exits the reboot, 15 times by default (counting from 0)
Exec_mode: Application startup mode, set here is Cluster_mode (cluster), default is fork
Error_file: Custom error log file for application
Out_file: Customizing Application log files
Pid_file: Customizing the application's PID file
Watch: Enable monitoring mode, default is False. If set to True, PM2 is automatically overloaded when the application changes. Here you can also set up the files you want to monitor.
Detailed parameter list: see annex VIII

Vi. examples

The Test.json above is an example

# cat >/data/wwwroot/nodejs/test.sh << EOF
#!/bin/bash
While:
Todo
echo "Test" >> 1.log
Sleep 5
Done
Eof
# chmod +x test.sh #添加执行权限
# PM2 Start Test.json #启动, as shown in the following figure:

# PM2 list #查看pm2进程, as shown below:

Vii. remarks
Other available parameters See official website: Http://pm2.keymetrics.io
Viii. Annex

Field Type Example Description
Name String "MyApi" Name your app'll have in PM2
Script String "Bin/app.js" Path of your app
Args List ["--enable-logs", "-N", "15"] Arguments given to your app as it is launched
Node_args List ["--harmony", "--max-stack-size=1024"] Arguments given to node as it is launched
Cwd String "/var/www/app/prod" The directory from which your app would be launched
Exec_mode String "Cluster" ' fork ' mode ' used by default, ' cluster ' mode can be configured with instances field
Instances Number 4 Number of instances for your clustered app., 0 means as much instances as you have CPU cores. A negative value means CPU cores-value (e.g-1 on a 4 cores machine would spawn 3 instances)
Exec_interpreter String "Node" Defaults to "Node". can be "Python", "Ruby", "bash" or whatever interpreter for you wish. ' None ' would execute your app as a binary executable
Log_date_format String "Yyyy-mm-dd hh:mm Z" Format in which timestamps is displayed in the logs
Error_file String "/var/log/node-app/node-app.stderr.log" Path to the specified error log file. PM2 generates one by default if not specified and your can find it by typing pm2 desc <app
Out_file String "/var/log/node-app/node-app.stdout.log" The path to the specified output log file. PM2 generates one by default if not specified and your can find it by typing pm2 desc <app
Pid_file String "Pids/node-geo-api.pid" Path to the specified PID file. PM2 generates one by default if not specified and your can find it by typing pm2 desc <app
Merge_logs Boolean False Defaults to False. If true, it would merge logs from all instances of the the same app into the same file
Cron_restart String "1 0 * * *" A cron pattern to restart your app, "cluster" mode for now. Soon to is avaible in "fork" mode as OK
Watch Boolean True Enables the watch feature, defaults to "false". If true, it would restart your app everytime a file change was detected on the folder or subfolder of the Your app.
Ignore_watch List ["[\/\\]\./", "Node_modules"] List of regex to ignore some file or folder names by the Watch feature
Min_uptime Number 1000 Min Uptime of the app to is considered started (i.e. if the app crashes in this time frame, the app is only restarted The number set in Max_restarts (default), after that it ' s errored
Max_restarts Number 10 Number of consecutive unstable restarts (less than 1sec interval or custom time via Min_uptime) before your app is Conside Red errored and stop being
Max_memory_restart String "150M" Your app is restarted by PM2 if it exceeds the amount of memory. human-friendly format:it can be "10M", "100K", "2G" and so on ...
Env Object {"Node_env": "Production", "ID": "42"} env variables which'll appear in your app
AutoRestart Boolean False True by default. If False, PM2 won't restart your app if it crashes or ends peacefully
Vizion Boolean False True by default. If False, PM2 'll start Without Vizion features (versioning control Metadatas)
Post_update List ["NPM Install", "Echo launching the app"] A list of commands which would be executed on your perform a pull/upgrade operation from Keymetrics Dashboard
Force Boolean True Defaults to False. If true, you can start the same script several times which are usually not allowed by PM2
Next_gen_js Boolean True Defaults to False. If true, PM2 'll launch your app using embedded BABELJS features which means you can run ES6/ES7 JavaScript code
Restart_delay Number 4000 Before restarting a crashed app (in milliseconds). Defaults to 0.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.