当前位置: 首页 > 工具软件 > pm2-webshell > 使用案例 >

PM2使用

毕宇
2023-12-01

PM2使用

pm2是一个进程管理工具,可以用它来管理你的node进程,并查看node进程的状态,当然也支持性能监控,进程守护,负载均衡等功能

pm2需要全局安装

npm install pm2@latest -g
# 更新pm2
pm2 update

一个简单的app.js测试用示例

const http = require('http');

const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

常用命令

  • 启动进程/应用 pm2 start app.js
  • 重命名进程/应用 pm2 start app.js --name www
  • 添加进程/应用watch pm2 start app --watch
  • 结束进程/应用 pm2 stop app
  • 结束所有进程/应用 pm2 stop all
  • 删除进程/应用 pm2 delete app
  • 删除所有进程/应用 pm2 delete all
  • 列出所有进程/应用 pm2 list|ls|status
  • 查看某个进程/应用具体情况 pm2 describe app
  • 查看进程/应用的资源消耗情况 pm2 monit
  • 实时查看查看pm2的日志 pm2 logs
  • 实时查看某个进程/应用的日志 pm2 logs app
  • 重新启动进程/应用 pm2 restart app
  • 重新启动/加载所有进程/应用 pm2 restart|reload all

生成简单的ecosystem.config.js

pm2 init simple
module.exports = {
  apps : [{
    name   : "app1",
    script : "./app.js"
  }]
}

ecosystem.config.js管理配置文件的使用

# Start all applications
pm2 start ecosystem.config.js

# Stop all
pm2 stop ecosystem.config.js

# Restart all
pm2 restart ecosystem.config.js

# Reload all
pm2 reload ecosystem.config.js

# Delete all
pm2 delete ecosystem.config.js

单独对ecosystem.config.js中的app操作

pm2 start ecosystem.config.js --only api-app
pm2 start ecosystem.config.js --only "api-app,worker-app"

ecosystem.config.js中使用env_*区分运行环境

module.exports = {
  apps : [{
    name   : "app1",
    script : "./app.js",
    env_production: {
       NODE_ENV: "production"
    },
    env_development: {
       NODE_ENV: "development"
    }
  }]
}

使用–env [env name]启动不同的环境

pm2 start ecosystem.config.js --env production
pm2 restart ecosystem.config.js --env development

可用的属性

General

FieldTypeExampleDescription
name(string)“my-api”application name (default to script filename without extension)
script(string)”./api/app.js”script path relative to pm2 start
cwd(string)“/var/www/”the directory from which your app will be launched
args(string)“-a 13 -b 12”string containing all arguments passed via CLI to script
interpreter(string)“/usr/bin/python”interpreter absolute path (default to node)
interpreter_args(string)”–harmony”option to pass to the interpreter
node_args(string)alias to interpreter_args

Advanced features

FieldTypeExampleDescription
instancesnumber-1number of app instance to be launched
exec_modestring“cluster”mode to start your app, can be “cluster” or “fork”, default fork
watchboolean or []trueenable watch & restart feature, if a file change in the folder or subfolder, your app will get reloaded
ignore_watchlist[”[\/\\]\./”, “node_modules”]list of regex to ignore some file or folder names by the watch feature
max_memory_restartstring“150M”your app will be restarted if it exceeds the amount of memory specified. human-friendly format : it can be “10M”, “100K”, “2G” and so on…
envobject{“NODE_ENV”: “development”, “ID”: “42”}env variables which will appear in your app
env_object{“NODE_ENV”: “production”, “ID”: “89”}inject when doing pm2 restart app.yml --env
source_map_supportbooleantruedefault to true, [enable/disable source map file]
instance_varstring“NODE_APP_INSTANCE”see documentation
filter_envarray of string[ “REACT_” ]Excludes global variables starting with “REACT_” and will not allow their penetration into the cluster.

Log files

FieldTypeExampleDescription
log_date_format(string)“YYYY-MM-DD HH:mm Z”log date format (see log section)
error_file(string)error file path (default to $HOME/.pm2/logs/XXXerr.log)
out_file(string)output file path (default to $HOME/.pm2/logs/XXXout.log)
combine_logsbooleantrueif set to true, avoid to suffix logs file with the process id
merge_logsbooleantruealias to combine_logs
pid_file(string)pid file path (default to $HOME/.pm2/pid/app-pm_id.pid)

Control flow

FieldTypeExampleDescription
min_uptime(string)min uptime of the app to be considered started
listen_timeoutnumber8000time in ms before forcing a reload if app not listening
kill_timeoutnumber1600time in milliseconds before sending a final SIGKILL
shutdown_with_messagebooleanfalseshutdown an application with process.send(‘shutdown’) instead of process.kill(pid, SIGINT)
wait_readybooleanfalseInstead of reload waiting for listen event, wait for process.send(‘ready’)
max_restartsnumber10number of consecutive unstable restarts (less than 1sec interval or custom time via min_uptime) before your app is considered errored and stop being restarted
restart_delaynumber4000time to wait before restarting a crashed app (in milliseconds). defaults to 0.
autorestartbooleanfalsetrue by default. if false, PM2 will not restart your app if it crashes or ends peacefully
cron_restartstring“1 0 * * *”a cron pattern to restart your app. Application must be running for cron feature to work
vizionbooleanfalsetrue by default. if false, PM2 will start without vizion features (versioning control metadatas)
post_updatelist[“npm install”, “echo launching the app”]a list of commands which will be executed after you perform a Pull/Upgrade operation from Keymetrics dashboard
forcebooleantruedefaults to false. if true, you can start the same script several times which is usually not allowed by PM2

Deployment

Entry nameDescriptionTypeDefault
keySSH key pathString$HOME/.ssh
userSSH userString
hostSSH host[String]
ssh_optionsSSH options with no command-line flag, see ‘man ssh’String or [String]
refGIT remote/branchString
repoGIT remoteString
pathpath in the serverString
pre-setupPre-setup command or path to a script on your local machineString
post-setupPost-setup commands or path to a script on the host machineString
pre-deploy-localpre-deploy actionString
post-deploypost-deploy actionString

pm2集群模式

# 开启命令
pm2 start app.js -i max

使用js文件的方式

module.exports = {
  apps : [{
    script    : "api.js",
    instances : "max",
    exec_mode : "cluster"
  }]
}

pm2进程开机启动

保存当前进程状态

pm2 save

生成systemnd开机启动service模板

# pm2 startup 
[PM2] Init System found: systemd
Platform systemd
Template
[Unit]
Description=PM2 process manager
Documentation=https://pm2.keymetrics.io/
After=network.target

[Service]
Type=forking
User=root
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/node-v14.19.1-linux-x64/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
Environment=PM2_HOME=/root/.pm2
PIDFile=/root/.pm2/pm2.pid
Restart=on-failure

ExecStart=/usr/local/node-v14.19.1-linux-x64/lib/node_modules/pm2/bin/pm2 resurrect
ExecReload=/usr/local/node-v14.19.1-linux-x64/lib/node_modules/pm2/bin/pm2 reload all
ExecStop=/usr/local/node-v14.19.1-linux-x64/lib/node_modules/pm2/bin/pm2 kill

[Install]
WantedBy=multi-user.target

Target path
/etc/systemd/system/pm2-root.service
Command list
[ 'systemctl enable pm2-root' ]
[PM2] Writing init configuration in /etc/systemd/system/pm2-root.service
[PM2] Making script booting at startup...
[PM2] [-] Executing: systemctl enable pm2-root...
[PM2] [v] Command successfully executed.
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save

[PM2] Remove init script via:
$ pm2 unstartup systemd

pm2单页帮助文档

PM2单页文档

pm2命令帮助

# pm2 --help

  Usage: pm2 [cmd] app

  Options:

    -V, --version                                                output the version number
    -v --version                                                 print pm2 version
    -s --silent                                                  hide all messages
    --ext <extensions>                                           watch only this file extensions
    -n --name <name>                                             set a name for the process in the process list
    -m --mini-list                                               display a compacted list without formatting
    --interpreter <interpreter>                                  set a specific interpreter to use for executing app, default: node
    --interpreter-args <arguments>                               set arguments to pass to the interpreter (alias of --node-args)
    --node-args <node_args>                                      space delimited arguments to pass to node
    -o --output <path>                                           specify log file for stdout
    -e --error <path>                                            specify log file for stderr
    -l --log [path]                                              specify log file which gathers both stdout and stderr
    --filter-env [envs]                                          filter out outgoing global values that contain provided strings (default: )
    --log-type <type>                                            specify log output style (raw by default, json optional)
    --log-date-format <date format>                              add custom prefix timestamp to logs
    --time                                                       enable time logging
    --disable-logs                                               disable all logs storage
    --env <environment_name>                                     specify which set of environment variables from ecosystem file must be injected
    -a --update-env                                              force an update of the environment with restart/reload (-a <=> apply)
    -f --force                                                   force actions
    -i --instances <number>                                      launch [number] instances (for networked app)(load balanced)
    --parallel <number>                                          number of parallel actions (for restart/reload)
    --shutdown-with-message                                      shutdown an application with process.send('shutdown') instead of process.kill(pid, SIGINT)
    -p --pid <pid>                                               specify pid file
    -k --kill-timeout <delay>                                    delay before sending final SIGKILL signal to process
    --listen-timeout <delay>                                     listen timeout on application reload
    --max-memory-restart <memory>                                Restart the app if an amount of memory is exceeded (in bytes)
    --restart-delay <delay>                                      specify a delay between restarts (in milliseconds)
    --exp-backoff-restart-delay <delay>                          specify a delay between restarts (in milliseconds)
    -x --execute-command                                         execute a program using fork system
    --max-restarts [count]                                       only restart the script COUNT times
    -u --user <username>                                         define user when generating startup script
    --uid <uid>                                                  run target script with <uid> rights
    --gid <gid>                                                  run target script with <gid> rights
    --namespace <ns>                                             start application within specified namespace
    --cwd <path>                                                 run target script from path <cwd>
    --hp <home path>                                             define home path when generating startup script
    --wait-ip                                                    override systemd script to wait for full internet connectivity to launch pm2
    --service-name <name>                                        define service name when generating startup script
    -c --cron <cron_pattern>                                     restart a running process based on a cron pattern
    -c --cron-restart <cron_pattern>                             (alias) restart a running process based on a cron pattern
    -w --write                                                   write configuration in local folder
    --no-daemon                                                  run pm2 daemon in the foreground if it doesn't exist already
    --source-map-support                                         force source map support
    --only <application-name>                                    with json declaration, allow to only act on one application
    --disable-source-map-support                                 force source map support
    --wait-ready                                                 ask pm2 to wait for ready event from your app
    --merge-logs                                                 merge logs from different instances but keep error and out separated
    --watch [paths]                                              watch application folder for changes (default: )
    --ignore-watch <folders|files>                               List of paths to ignore (name or regex)
    --watch-delay <delay>                                        specify a restart delay after changing files (--watch-delay 4 (in sec) or 4000ms)
    --no-color                                                   skip colors
    --no-vizion                                                  start an app without vizion feature (versioning control)
    --no-autorestart                                             start an app without automatic restart
    --no-treekill                                                Only kill the main process, not detached children
    --no-pmx                                                     start an app without pmx
    --no-automation                                              start an app without pmx
    --trace                                                      enable transaction tracing with km
    --disable-trace                                              disable transaction tracing with km
    --sort <field_name:sort>                                     sort process according to field's name
    --attach                                                     attach logging after your start/restart/stop/reload
    --v8                                                         enable v8 data collecting
    --event-loop-inspector                                       enable event-loop-inspector dump in pmx
    --deep-monitoring                                            enable all monitoring tools (equivalent to --v8 --event-loop-inspector --trace)
    -h, --help                                                   output usage information

  Commands:

    start [options] [name|namespace|file|ecosystem|id...]        start and daemonize an app
    trigger <id|proc_name|namespace|all> <action_name> [params]  trigger process action
    deploy <file|environment>                                    deploy your json
    startOrRestart <json>                                        start or restart JSON file
    startOrReload <json>                                         start or gracefully reload JSON file
    pid [app_name]                                               return pid of [app_name] or all
    create                                                       return pid of [app_name] or all
    startOrGracefulReload <json>                                 start or gracefully reload JSON file
    stop [options] <id|name|namespace|all|json|stdin...>         stop a process
    restart [options] <id|name|namespace|all|json|stdin...>      restart a process
    scale <app_name> <number>                                    scale up/down a process in cluster mode depending on total_number param
    profile:mem [time]                                           Sample PM2 heap memory
    profile:cpu [time]                                           Profile PM2 cpu
    reload <id|name|namespace|all>                               reload processes (note that its for app using HTTP/HTTPS)
    id <name>                                                    get process id by name
    inspect <name>                                               inspect a process
    delete|del <name|id|namespace|script|all|json|stdin...>      stop and delete a process from pm2 process list
    sendSignal <signal> <pm2_id|name>                            send a system signal to the target process
    ping                                                         ping pm2 daemon - if not up it will launch it
    updatePM2                                                    update in-memory PM2 with local PM2
    update                                                       (alias) update in-memory PM2 with local PM2
    install|module:install [options] <module|git:/>              install or update a module and run it forever
    module:update <module|git:/>                                 update a module and run it forever
    module:generate [app_name]                                   Generate a sample module in current folder
    uninstall|module:uninstall <module>                          stop and uninstall a module
    package [target]                                             Check & Package TAR type module
    publish|module:publish [options] [folder]                    Publish the module you are currently on
    set [key] [value]                                            sets the specified config <key> <value>
    multiset <value>                                             multiset eg "key1 val1 key2 val2
    get [key]                                                    get value for <key>
    conf [key] [value]                                           get / set module config values
    config <key> [value]                                         get / set module config values
    unset <key>                                                  clears the specified config <key>
    report                                                       give a full pm2 report for https://github.com/Unitech/pm2/issues
    link [options] [secret] [public] [name]                      link with the pm2 monitoring dashboard
    unlink                                                       unlink with the pm2 monitoring dashboard
    monitor [name]                                               monitor target process
    unmonitor [name]                                             unmonitor target process
    open                                                         open the pm2 monitoring dashboard
    plus|register [options] [command] [option]                   enable pm2 plus
    login                                                        Login to pm2 plus
    logout                                                       Logout from pm2 plus
    dump|save [options]                                          dump all processes for resurrecting them later
    cleardump                                                    Create empty dump file
    send <pm_id> <line>                                          send stdin to <pm_id>
    attach <pm_id> [comman]                                      attach stdin/stdout to application identified by <pm_id>
    resurrect                                                    resurrect previously dumped processes
    unstartup [platform]                                         disable the pm2 startup hook
    startup [platform]                                           enable the pm2 startup hook
    logrotate                                                    copy default logrotate configuration
    ecosystem|init [mode]                                        generate a process conf file. (mode = null or simple)
    reset <name|id|all>                                          reset counters for process
    describe <name|id>                                           describe all parameters of a process
    desc <name|id>                                               (alias) describe all parameters of a process
    info <name|id>                                               (alias) describe all parameters of a process
    show <name|id>                                               (alias) describe all parameters of a process
    env <id>                                                     list all environment variables of a process id
    list|ls                                                      list all processes
    l                                                            (alias) list all processes
    ps                                                           (alias) list all processes
    status                                                       (alias) list all processes
    jlist                                                        list all processes in JSON format
    sysmonit                                                     start system monitoring daemon
    slist|sysinfos [options]                                     list system infos in JSON
    prettylist                                                   print json in a prettified JSON
    monit                                                        launch termcaps monitoring
    imonit                                                       launch legacy termcaps monitoring
    dashboard|dash                                               launch dashboard with monitoring and logs
    flush [api]                                                  flush logs
    reloadLogs                                                   reload all logs
    logs [options] [id|name|namespace]                           stream logs file. Default stream all logs
    kill                                                         kill daemon
    pull <name> [commit_id]                                      updates repository for a given app
    forward <name>                                               updates repository to the next commit for a given app
    backward <name>                                              downgrades repository to the previous commit for a given app
    deepUpdate                                                   performs a deep update of PM2
    serve|expose [options] [path] [port]                         serve a directory over http via port
    autoinstall
    examples                                                     display pm2 usage examples
    *
 类似资料: