现在,越来越多的程序猿喜欢直接直接将容器(tomcat)嵌入到Java程序中,使其直接使用java -jar 就可以直接运行JavaWeb程序,典型的就是Spring Boot应用,以及jenkins官方提供的war包,通常大家都喜欢使用nohup java -jar jenkins.war &来运行,但这样运行并不优雅,这里就介绍如何使用pm2来运行Java程序。

环境依赖

  • Node.js
  • Java

安装pm2

使用如下命令安装pm2

1
npm install pm2 -g

运行Java应用

本次案例是运行Jenkins.war。在Jenkins官网下载war包到/data/jenkins后,在该war包同级目录/data/jenkins新建文件jenkins.json,内容如下:

1
2
3
4
5
6
7
8
9
10
11
{
"name": "jenkins",
"script": "/usr/bin/java",
"args": [
"-jar",
"jenkins.war",
"--httpPort=8080"
],
"exec_interpreter": "",
"exec_mode": "fork"
}

说明:

  • name 表示进程的名称
  • script 表示运行的脚本的指令名称,通常为python3phpjava等,为避免环境变量的问题,前填写命令的全路径
  • args 表示参数,参数之间用,号分隔
  • exec_interpreter Node解析器
  • exec_mode 执行模式,值为cluster或者fork,非Node.js应用统一为fork

启动java程序

1
pm2 start jenkins.json

启动完成后,可通过pm2 list查看Jenkins进程

1
2
3
4
5
┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬────────┬────────────┬──────┐
│ App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │
├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼────────┼────────────┼──────┤
│ jenkins │ 0 │ N/A │ fork │ 26188 │ online │ 0 │ 26m │ 152.2% │ 880.0 MB │ root │
└──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴────────┴────────────┴──────┘

关于pm2的命令:

  • pm2 list 查看所有被PM2管理的进程列表
  • pm2 start xxx 启动一个应用
    • pm2 start [id|name]
    • pm2 start app.js -i max # 根据有效CPU数目启动最大进程数目
    • pm2 start app.js -i 3 # 启动3个进程
    • pm2 start app.js -x #用fork模式启动 app.js 而不是使用 cluster
    • pm2 start app.js -x – -a 23 # 用fork模式启动 app.js 并且传递参数 (-a 23)
    • pm2 start app.js –name serverone # 启动一个进程并把它命名为 serverone
    • pm2 start app.json # 启动进程, 在 app.json里设置选项
    • pm2 start app.js -i max -e err.log -o out.log # 启动 并 生成一个配置文件,你也可以执行用其他语言编写的app ( fork 模式):
    • pm2 start my-bash-script.sh -x –interpreter bash
    • pm2 start my-python-script.py -x –interpreter python
    • pm2 start app.js –max_memory_restart 1024M : 当内存超过1024M时自动重启。 如果工程中有比较棘手的内
      存泄露问题,这个算是一个折中方案。
  • pm2 stop xxx 停止一个应用
  • pm2 restart xxx 重启一个应用
  • pm2 describe xxx 查看应用详情
  • pm2 startup, pm2 save 两条命令,用来保证服务器启动时,pm2管理的程序自动运行

大概先介绍这么多吧,后面有时间再详细介绍一下pm2,以后启动spring boot程序就再也别用nohup啦。