大苹果
NodeJs的服务管理之PM2
一、简介pm2是一个带有负载均衡功能的应用进程管理器,类似有Supervisor,forever。二、安装LinuxBinaries下载地址:https://nodejs.org/distcdoneinstack/srcwgethttps://nodejs.org/dist/v4.2.4/node-v4.2.4-linux-x64.tar.gztarxzfnode-v4.2.4-linux-x64.tar.gzcpnode-v4.2.4-linux-x64/bin/node/usr/local/bin/cp-Rnode-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/npmnpminstallpm2@latest-g#安装最新版本pm2模块PS:如果你的主机无法连接公网,先找到能连公网的主机安装上面的方法安装pm2,然后拷贝到你要安装的主机。拷贝如下目录:/usr/local/bin/node/usr/local/lib/node_modules再创建相关软连接三、PM2常用命令假设你现在已经写好了一个app.js的文件,需要启动,你可以使用pm2进行管理1.启动#pm2startapp.js#pm2startapp.js--namemy-api#my-api为PM2进程名称#pm2startapp.js-i0#根据CPU核数启动进程个数#pm2startapp.js--watch#实时监控app.js的方式启动,当app.js文件有变动时,pm2会自动reload2.查看进程#pm2list#pm2show0或者#pm2info0#查看进程详细信息,0为PM2进程id3.监控#pm2monit4.停止#pm2stopall#停止PM2列表中所有的进程#pm2stop0#停止PM2列表中进程为0的进程5.重载#pm2reloadall#重载PM2列表中所有的进程#pm2reload0#重载PM2列表中进程为0的进程6.重启#pm2restartall#重启PM2列表中所有的进程#pm2restart0#重启PM2列表中进程为0的进程7.删除PM2进程#pm2delete0#删除PM2列表中进程为0的进程#pm2deleteall#删除PM2列表中所有的进程8.日志操作#pm2logs[--raw]#Displayallprocesseslogsinstreaming#pm2flush#Emptyalllogfile#pm2reloadLogs#Reloadalllogs9.升级PM2#npminstallpm2@lastest-g#安装最新的PM2版本#pm2updatePM2#升级pm210.更多命令参数请查看帮助#pm2--help四、PM2目录结构默认的目录是:当前用于的家目录下的.pm2目录(此目录可以自定义,请参考:五、自定义启动文件),详细信息如下:$HOME/.pm2#willcontainallPM2relatedfiles$HOME/.pm2/logs#willcontainallapplicationslogs$HOME/.pm2/pids#willcontainallapplicationspids$HOME/.pm2/pm2.log#PM2logs$HOME/.pm2/pm2.pid#PM2pid$HOME/.pm2/rpc.sock#Socketfileforremotecommands$HOME/.pm2/pub.sock#Socketfileforpublishableevents$HOME/.pm2/conf.js#PM2Configuration五、自定义启动文件创建一个test.json的示例文件,格式如下:{"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,默认是nodejsmin_uptime:最小运行时间,这里设置的是60s即如果应用程序在60s内退出,pm2会认为程序异常退出,此时触发重启max_restarts设置数量max_restarts:设置应用程序异常退出重启的次数,默认15次(从0开始计数)exec_mode:应用程序启动模式,这里设置的是cluster_mode(集群),默认是forkerror_file:自定义应用程序的错误日志文件out_file:自定义应用程序日志文件pid_file:自定义应用程序的pid文件watch:是否启用监控模式,默认是false。如果设置成true,当应用程序变动时,pm2会自动重载。这里也可以设置你要监控的文件。详细参数列表:见附件八六、实例已上面的test.json为例#cat>/data/wwwroot/nodejs/test.sh<<EOF#!/bin/bashwhile:doecho"Test">>1.logsleep5doneEOF#chmod+xtest.sh#添加执行权限#pm2starttest.json#启动,如下图:#pm2list#查看pm2进程,如下图:七、备注其他可参数见官网:http://pm2.keymetrics.io八、附件FieldTypeExampleDescriptionnamestring"myAPI"nameyourappwillhaveinPM2scriptstring"bin/app.js"pathofyourappargslist["--enable-logs","-n","15"]argumentsgiventoyourappwhenitislaunchednode_argslist["--harmony","--max-stack-size=1024"]argumentsgiventonodewhenitislaunchedcwdstring"/var/www/app/prod"thedirectoryfromwhichyourappwillbelaunchedexec_modestring"cluster""fork"modeisusedbydefault,"cluster"modecanbeconfiguredwithinstancesfieldinstancesnumber4numberofinstancesforyourclusteredapp,0meansasmuchinstancesasyouhaveCPUcores.anegativevaluemeansCPUcores-value(e.g-1ona4coresmachinewillspawn3instances)exec_interpreterstring"node"defaultsto"node".canbe"python","ruby","bash"orwhateverinterpreteryouwishtouse."none"willexecuteyourappasabinaryexecutablelog_date_formatstring"YYYY-MM-DDHH:mmZ"formatinwhichtimestampswillbedisplayedinthelogserror_filestring"/var/log/node-app/node-app.stderr.log"pathtothespecifiederrorlogfile.PM2generatesonebydefaultifnotspecifiedandyoucanfinditbytypingpm2desc<appid>out_filestring"/var/log/node-app/node-app.stdout.log"pathtothespecifiedoutputlogfile.PM2generatesonebydefaultifnotspecifiedandyoucanfinditbytypingpm2desc<appid>pid_filestring"pids/node-geo-api.pid"pathtothespecifiedpidfile.PM2generatesonebydefaultifnotspecifiedandyoucanfinditbytypingpm2desc<appid>merge_logsbooleanfalsedefaultstofalse.iftrue,itwillmergelogsfromallinstancesofthesameappintothesamefilecron_restartstring"10***"acronpatterntorestartyourapp.onlyworksin"cluster"modefornow.soontobeavaiblein"fork"modeaswellwatchbooleantrueenablesthewatchfeature,defaultsto"false".iftrue,itwillrestartyourappeverytimeafilechangeisdetectedonthefolderorsubfolderofyourapp.ignore_watchlist["[\/\\]\./","node_modules"]listofregextoignoresomefileorfoldernamesbythewatchfeaturemin_uptimenumber1000minuptimeoftheapptobeconsideredstarted(i.e.iftheappcrashesinthistimeframe,theappwillonlyberestartedthenumbersetinmax_restarts(default15),afterthatit'serrored)max_restartsnumber10numberofconsecutiveunstablerestarts(lessthan1secintervalorcustomtimeviamin_uptime)beforeyourappisconsiderederroredandstopbeingmax_memory_restartstring"150M"yourappwillberestartedbyPM2ifitexceedstheamountofmemoryspecified.human-friendlyformat:itcanbe"10M","100K","2G"andsoon...envobject{"NODE_ENV":"production","ID":"42"}envvariableswhichwillappearinyourappautorestartbooleanfalsetruebydefault.iffalse,PM2willnotrestartyourappifitcrashesorendspeacefullyvizionbooleanfalsetruebydefault.iffalse,PM2willstartwithoutvizionfeatures(versioningcontrolmetadatas)post_updatelist["npminstall","echolaunchingtheapp"]alistofcommandswhichwillbeexecutedafteryouperformaPull/UpgradeoperationfromKeymetricsdashboardforcebooleantruedefaultstofalse.iftrue,youcanstartthesamescriptseveraltimeswhichisusuallynotallowedbyPM2next_gen_jsbooleantruedefaultstofalse.iftrue,PM2willlaunchyourappusingembeddedBabelJSfeatureswhichmeansyoucanrunES6/ES7javascriptcoderestart_delaynumber4000timetowaitbeforerestartingacrashedapp(inmilliseconds).defaultsto0.
NodeJS,PM2,服务管理Web服务
16064
7年前