1 Install

类似supervisor

1.1 Intro

pm2 is a production process manager for node.js applications with a built-in load balancer(内置负载均衡).
It allow you to keep applications alive forever, to reload them without downtime and to facilitate(加快) common system admin tasks.

根目录.pm2目录结构说明:

1
2
3
4
5
6
7
8
9
10
11
$HOME
.pm2 // contain all PM2 related files
├── logs // contain all applications logs
├── module_conf.json // PM2 configuration
├── pids // contail all applications pids
├── pm2.log // PM2 log
├── pm2.pid // PM2 pid
├── pub.sock // socket file for publishable events
├── rpc.sock // socket file for remote commands
└── touch
└── dump.pm2 // 开机自启动

可以利用pm2来管理gunicorn进程.

1.3 Using

1
2
3
4
5
6
7
8
# 安装
sudo npm install -g pm2@latest

# 执行命令
pm2 list

# Start an application
pm2 start app.js

3 Options

一些选项关系到运行其他脚本是否成功

1
2
3
4
5
6
7
8
9
10
11
12
-n --name <name>                    # set a <name> for scripts, care about it.
-i --instances <number> # launch [number] instances
--max-memory-restart <memory> # specify max memory amount used to autorestart
--no-autorestart # Do not automatically restart apps
--env <environment_name> # specify environment to get specific env variables. Look Big Chapter 6 at outside fields.
-x --execute-command # execute a program using fork system(Used to start other interpreter)
--interpreter <interpreter> # execute app(bash, python, ...)
--watch # watch application folder for changes(converient)
--ignore-watch <foleders|files> # ignore watch, chould be a spcifiec name, look Big Chapter 7 at outside fields.
--node-args <node_args> # V8

-u --user <user> # define user when generting startup script

3 Command

简单介绍所有命令的简单用法,各个命令具体用法见下面章节说明

3.1 Start and configure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 1 Install PM2
npm install pm2 -g

# 3 start/update
# Start, Daemonize and auto-restart application (Node)
pm2 start app.js
# Start, Daemonize and auto-restart application (Python)
pm2 start app.py
# Start, Daemonize and auto-restart Node application
pm2 start npm -- start

# Cluster Mode (Node.js only), 集群下,自动或者手动多实例进程,保证负载均衡
# Start 4 instances of application in cluster mode
pm2 start app.js -i 4
# Lanuch "max" instances, "max" depending on the number of CPUS.
pm2 start app.js [app-name] -i 0
pm2 start app.js [app-name] -i max

# load balancer
# Start maximus processess depending on available cpus
pm2 start app.js -i 0
# Start two process intances, achieve load balancing.
pm2 start app.js -i 2

# Pass a arguments 23 to app.js scripts,use this very frequent.
pm2 start app.js -- -a 23
# pass options to V8
pm2 start app.js --node-args='--debug=7001'
# Start application with options accross by app.json
pm2 start app.json

# log
pm2 start app.js --log-date-format "YYYY-MM-DD"
# Start and spcecial error and out log.
pm2 start app.js -e err.log -o out.log

# Start a process an name it as server one.
pm2 start app.js --name serverone

# Save processes, kill PM2 and restore processes
pm2 update


# 3 Startup/Boot management
# Detect init system, generate and configure pm2 boot on startup
pm2 startup
pm2 startup ubuntu -u www
# Disable and remove startup system
pm2 unstartup

# 4 dump or save environment
# Dump all process status and env.
pm2 dump
# Save current process list
pm2 save
# Restore previously save processes
pm2 resurrect

# Generate a sample json configuration file
pm2 generate


# 5 reload(restart) all process
# Zero Second Downtime Reload,平稳重载或者热重载,所有的进程管理应用必备招牌
pm2 reload all
# This features only works for apps in "clus mode", that use http/https/socket
pm2 reload [app-name]
# 优雅重载,sometimes you can experience a very long reload, or a reload that
pm2 gracefulReload [all|name]

pm2 scale [app-name] 10 # Scale(规模) Cluster app to 10 process

3.2 logs and monitor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#  1 Show pm2 process
# Descripe
pm2 describe 0
# Show information abount application
pm2 show [app-name]

# 3 List pm2 process
# Process Monitoring(Important)
pm2 list|ls|l|status # List all processes started with PM2
pm2 monit # Display memory and cpu usage of each app

# 3 Reload and watch
# Automatically restart your app when a files change in the current directories and sub.
pm2 start app.js --watch
pm2 stop --watch 0|app-name

# 4 Watch specific paths
{
"watch": ["server", "client"],
"ignoreWatch": ["note_modules", client/img"]
}

# 4 Log management
# 相比supervisorctl等进程管理,日志的详细查看在pm2中非常棒
pm2 logs # Display logs of all apps
pm2 logs [app-name] # Display logs for a specific app
pm2 logs --json # Logs in JSON format
pm2 flush # Clear all logs
pm2 reloadLogs # Reload all logs(Send SIGUSR2 to all process)

# 5 设置日志时间戳前缀
export PM2_LOG_DATE_FORMAT="YYYY-MM-DD HH:mm Z"
pm2 dump
pm2 resurrect|save

3.3 Process management

PM2 is a process manager. It manages your application states, so you can start, stop, restart and delete process

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# start 
pm2 start app.js --name="api" # Start application and name it "api"
pm2 start app.js -- -a 34 # Start app and pass option "-a 34" as argument
pm2 start app.js --watch # Restart application on file change
pm2 start script.sh # Start bash script
pm2 start app.json # Start all applications declared in app.json

# stop
# Just stop process, but not delete apps from pm2 manager list.
pm2 reset [app-name] # Reset all counters
pm2 stop all # Stop all apps
pm2 stop 0 # Stop process with id 0

# restart
pm2 restart [app-name] # Restart a spcial apps
pm2 restart all # Restart all apps
pm2 gracefulReload all # Graceful reload all apps in cluster mode

# delete
# Delete a apps name from pm2 list.
pm2 delete all # Kill and delete all apps
pm2 delete 0 # Delete app with id 0

3.4 delpoyment and module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Deployment
# 远程部署,暂时未使用到
pm2 deploy app.json prod setup # Setup "prod" remote server
pm2 deploy app.json prod # Update "prod" remote server
pm2 deploy app.json prod revert 2 # Revert "prod" remote server by 2

# list all process and show some special process
pm2 [list|ls|l|status]
pm2 show <id>

# Module system
# 模块扩展系统,支持第三方扩展
pm2 module:generate [name] # Generate sample module with name [name]
pm2 install pm2-logrotate # Install module (here a log rotation system)
pm2 uninstall pm2-logrotate # Uninstall module
pm2 publish # Increment version, git push and npm publish

3.5 Start other script language

4 Start other script language

4.1 Format

1
2
3
4
5
# Special other script language interpreter
pm2 start echo.pl --interpreter=perl

# Call shell script
pm2 start echo.sh --name "shell-test"

Example:

1
2
3
4
5
# start gunicorn process
pm2 start gunicorn_start_service.sh --name 'test' -x -- -p 8080

# start python process
pm2 start manage.py --name 'test-rq' --interpreter=/usr/bin/python -i 1 -x -- rqworker rq1

4.2 Default interpreter

Default interpreter and it file suffix

1
2
3
4
5
6
7
8
9
{
".sh": "bash",
".py": "python",
".rb": "ruby",
".coffee" : "coffee",
".php": "php",
".pl" : "perl",
".js" : "node"
}

4.3 configure

To run a non-js interperter you must set “exec_mode” to “fork_mode” and
“exec_interpreter” to your interperter of choice.For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"apps" : [{
"name" : "bash-worker",
"script" : "./a-bash-script",
"exec_interpreter": "bash",
"exec_mode" : "fork_mode"
}, {
"name" : "ruby-worker",
"script" : "./some-ruby-script",
"exec_interpreter": "ruby",
"exec_mode" : "fork_mode"
}]
}

4.4 max memory limit

PM2 allow to restart an application based on a memory limit

CLI: pm2 start bin-array.js –max-memory-restart 20M

JSON configure:(process.json):

1
2
3
4
5
{
"name" : "max_mem",
"script" : "big-array.js",
"max_memory_restart" : "20M"
}

define parameters for my apps in “process.json”

1
pm2 start|stop|delete|restart process.json

5 Environment

实际开发中,应用需要在多个环境下部署, 比如: 开发环境, 测试环境, 生产环境, i
此时pm2可以根据env_xx来声明不同环境的配置, 然后在应用启动时,
通过–env参数来指定运行的环境。

5.1 环境变量声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
env:默认,生产环境
env_dev:开发环境
env_test:测试环境

# json配置:
"env": {
"NODE_ENV": "production",
"REMOTE_ADDR": "http://www.example.com/"
},
"env_dev": {
"NODE_ENV": "development",
"REMOTE_ADDR": "http://wdev.example.com/"
},
"env_test": {
"NODE_ENV": "test",
"REMOTE_ADDR": "http://wtest.example.com/"
}

# 应用中读取配置中的变量(node.js)
使用process.env.REMOTE_ADDR来读取变量

5.2 指明环境

pm2 start app.js –env dev

6 Auto Start after Reboot

1
2
3
4
# save process
pm2 save
# edit crontab and manual restart(ubuntu)
@reboot pm2 resurrect