🔍 登录 注册

NodeJs的服务管理之PM2

大 大苹果 2017-06-09 linux 👁 16087 ⏱ 12min

一、简介

pm2是一个带有负载均衡功能的应用进程管理器,类似有Supervisor,forever。

二、安装

Linux Binaries下载地址: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: 如果你的主机无法连接公网,先找到能连公网的主机安装上面的方法安装pm2,然后拷贝到你要安装的主机。拷贝如下目录:

/usr/local/bin/node
/usr/local/lib/node_modules

        再创建相关软连接

三、PM2常用命令

假设你现在已经写好了一个app.js的文件,需要启动,你可以使用pm2进行管理

1. 启动


  1. # pm2 start app.js
    # pm2 start app.js --name my-api   #my-api为PM2进程名称
    # pm2 start app.js -i 0           #根据CPU核数启动进程个数
    # pm2 start app.js --watch   #实时监控app.js的方式启动,当app.js文件有变动时,pm2会自动reload

2. 查看进程


  1. # pm2 list
    # pm2 show 0 或者 # pm2 info 0  #查看进程详细信息,0为PM2进程id

3. 监控

  1. # pm2 monit

4. 停止

  1. # pm2 stop all  #停止PM2列表中所有的进程
    # pm2 stop 0    #停止PM2列表中进程为0的进程

5. 重载

  1. # pm2 reload all    #重载PM2列表中所有的进程
    # pm2 reload 0     #重载PM2列表中进程为0的进程

6. 重启

  1. # pm2 restart all     #重启PM2列表中所有的进程
    # pm2 restart 0      #重启PM2列表中进程为0的进程

7. 删除PM2进程

  1. # pm2 delete 0     #删除PM2列表中进程为0的进程
    # pm2 delete all   #删除PM2列表中所有的进程

8. 日志操作

  1. # pm2 logs [--raw]   #Display all processes logs in streaming
    # pm2 flush              #Empty all log file
    # pm2 reloadLogs    #Reload all logs

9. 升级PM2

  1. # npm install pm2@lastest -g   #安装最新的PM2版本
    # pm2 updatePM2                    #升级pm2

10. 更多命令参数请查看帮助

# pm2 --help

四、PM2目录结构

默认的目录是:当前用于的家目录下的.pm2目录(此目录可以自定义,请参考:五、自定义启动文件),详细信息如下:


  1. $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

五、自定义启动文件

创建一个test.json的示例文件,格式如下:


  1. {
      "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
        }
    }

说明:

apps:json结构,apps是一个数组,每一个数组成员就是对应一个pm2中运行的应用
name:应用程序的名称
cwd:应用程序所在的目录
script:应用程序的脚本路径
exec_interpreter:应用程序的脚本类型,这里使用的shell,默认是nodejs
min_uptime:最小运行时间,这里设置的是60s即如果应用程序在60s内退出,pm2会认为程序异常退出,此时触发重启max_restarts设置数量
max_restarts:设置应用程序异常退出重启的次数,默认15次(从0开始计数)
exec_mode:应用程序启动模式,这里设置的是cluster_mode(集群),默认是fork
error_file:自定义应用程序的错误日志文件
out_file:自定义应用程序日志文件
pid_file:自定义应用程序的pid文件
watch:是否启用监控模式,默认是false。如果设置成true,当应用程序变动时,pm2会自动重载。这里也可以设置你要

监控的文件。

详细参数列表:见附件八

六、实例

已上面的test.json为例

  1. # cat > /data/wwwroot/nodejs/test.sh << EOF
    #!/bin/bash
    while :
    do
        echo "Test" >> 1.log
        sleep 5
    done
    EOF
  2. # chmod +x test.sh      #添加执行权限
    # pm2 start test.json    #启动,如下图:

image.png

# pm2 list    #查看pm2进程,如下图:

image.png

七、备注

其他可参数见官网:http://pm2.keymetrics.io

八、附件

FieldTypeExampleDescription
namestring"myAPI"name your app will have in PM2
scriptstring"bin/app.js"path of your app
argslist["--enable-logs", "-n", "15"]arguments given to your app when it is launched
node_argslist["--harmony", "--max-stack-size=1024"]arguments given to node when it is launched
cwdstring"/var/www/app/prod"the directory from which your app will be launched
exec_modestring"cluster""fork" mode is used by default, "cluster" mode can be configured with instances field
instancesnumber4number 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 will spawn 3 instances)
exec_interpreterstring"node"defaults to "node". can be "python", "ruby", "bash" or whatever interpreter you wish to use. "none" will execute your app as a binary executable
log_date_formatstring"YYYY-MM-DD HH:mm Z"format in which timestamps will be displayed in the logs
error_filestring"/var/log/node-app/node-app.stderr.log"path to the specified error log file. PM2 generates one by default if not specified and you can find it by typing pm2 desc <app id>
out_filestring"/var/log/node-app/node-app.stdout.log"path to the specified output log file. PM2 generates one by default if not specified and you can find it by typing pm2 desc <app id>
pid_filestring"pids/node-geo-api.pid"path to the specified pid file. PM2 generates one by default if not specified and you can find it by typing pm2 desc <app id>
merge_logsbooleanfalsedefaults to false. if true, it will merge logs from all instances of the same app into the same file
cron_restartstring"1 0 * * *"a cron pattern to restart your app. only works in "cluster" mode for now. soon to be avaible in "fork" mode as well
watchbooleantrueenables the watch feature, defaults to "false". if true, it will restart your app everytime a file change is detected on the folder or subfolder of your app.
ignore_watchlist["[\/\\]\./", "node_modules"]list of regex to ignore some file or folder names by the watch feature
min_uptimenumber1000min uptime of the app to be considered started (i.e. if the app crashes in this time frame, the app will only be restarted the number set in max_restarts (default 15), after that it's errored)
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
max_memory_restartstring"150M"your app will be restarted by PM2 if it exceeds the amount of memory specified. human-friendly format : it can be "10M", "100K", "2G" and so on...
envobject{"NODE_ENV": "production", "ID": "42"}env variables which will appear in your app
autorestartbooleanfalsetrue by default. if false, PM2 will not restart your app if it crashes or ends peacefully
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
next_gen_jsbooleantruedefaults to false. if true, PM2 will launch your app using embedded BabelJS features which means you can run ES6/ES7 javascript code
restart_delaynumber4000time to wait before restarting a crashed app (in milliseconds). defaults to 0.


读完了?给作者一点支持

本文采用 CC BY 4.0 协议转载 · © 大苹果

评论(0)

登录 后参与评论。

  • 还没有评论,来抢沙发。

🔗 相关文章

Mysql 表被标记为崩溃,最后一次自动化修复失败

当 MySQL 日志中出现“表被标记为崩溃且自动修复失败”的提示时,通常表示 MySQL 在启动过程中检测到某个表的文件系统或存储引擎层出现了问题。这种情况通常会导致表无法正常使用,需要手动进行修复。以下是处理这种情况的一些步骤和方法: ### 1. **查看具体错误信息** 首先,需要查看 MySQL 错误日志以获取更多的错误信息。这可以帮助确定崩溃的表和具体的问题。 ```bash # 查看 MySQL 错误日志 tail -f /var/log/mysql/error.log ``` ### 2. **修复表** 不同的存储引擎有不同的修复工具,以下是常用的修复方法: #### **使用 `myisamchk` 修复 MyISAM 表** 如果崩溃的表使用的是 MyISAM 存储引擎,可以使用 `myisamchk` 工具来修复表。 1. 停止 MySQL 服务: ```bash sudo systemctl stop mysql ``` 2. 使用 `myisamchk` 修复表:

2024/8/11👍 0

mermaid.min.js的使用及介绍

`mermaid.min.js` 是一个 JavaScript 库,用于在浏览器中轻松绘制复杂的图表和流程图。Mermaid 通过使用简单的标记语言来描述图表,使得用户无需深入学习图表绘制的底层技术即可创建专业的图形。 在这篇文章中,我们将介绍 `mermaid.min.js` 的功能、应用场景、如何在项目中使用,以及一些常用的示例。 ## Mermaid 的功能 Mermaid 支持多种类型的图表,包括但不限于: 1. **流程图(Flowchart)**: - 用于表示流程或过程中的步骤。 - 支持各种节点和连线风格。 2. **序列图(Sequence Diagram)**: - 用于表示对象之间的交互。 - 展示消息的发送和接收过程。 3. **类图(Class Diagram)**: - 用于表示类及其关系。 - 支持类的属性和方法定义。 4. **状态图(State Diagram)**: - 用于描述系统状态及其转换。 - 适用于复杂的状态机建模。 5. **甘

2024/8/9👍 0

docker之Dockerfile及docker compose配置文件的说明及使用

Docker 的配置文件对于镜像构建和容器化应用的管理至关重要。在 Docker 中,主要的配置文件是 Dockerfile 和 docker-compose.yml。Dockerfile 用于构建镜像,而 docker-compose.yml 用于定义多容器应用。下面将详细介绍这两个文件的配置选项和用法。 ## Dockerfile 配置详解 **Dockerfile** 是一个文本文件,其中包含一组指令,用于定义如何构建 Docker 镜像。以下是 Dockerfile 中常用的指令及其用法: ### FROM `FROM` 指令用于指定基础镜像,是 Dockerfile 中的第一条指令。 ```dockerfile FROM node:14 ``` 上例中,`node:14` 是官方的 Node.js 版本 14 的镜像。 ### LABEL `LABEL` 用于为镜像添加元数据,以键值对形式存在。 ```dockerfile LABEL maintainer="your-email@example.com" LABE

2024/8/9👍 0