当服务器崩溃/瘫痪时,Node JS自动重启所有Forever JS进程

25
我使用Forever JS在AWS EC2上保持我的节点服务器24/7运行。
我使用这个命令。

I am using forever js to keep my node server running 24/7 on AWS EC2.

I use this command

forever start index.js

然而,我注意到有时它会随机停止进程,导致我的网站崩溃。我不得不手动通过ssh登录到服务器并执行以下操作才能再次运行它:

forever restartall

然后它会进行备份。是否有任何方法可以定义超时时间,比如如果服务器/网站在5秒内不响应200,则自动重新启动所有永久进程?

我是新手,如果有人能给我提供逐步示例以满足我的情况,那将是太棒了。


2
如果这是一个*NIX机器,那么你可以简单地定义一个在cron作业上运行的shell脚本来检查进程状态并在必要时重新启动。 - Evan Bechtol
可能是自动在系统重启时启动forever(node)的重复问题。 - Mark B
@EvanBechtol 它在 AWS EC2 t2.micro linux ubuntu 上。我完全是新手,你能否给出代码示例,说明如何定义和运行 shell 脚本?谢谢,我会将其标记为最佳答案 :) - Faizan
1
@Fizan,没问题,我今天会发布一个例子。抱歉让你等了这么久。 - Evan Bechtol
请检查已有的答案:https://dev59.com/_mYr5IYBdhLWcg3wy9KA - Chinni
6个回答

34

一个(NodeJS)服务器不应该无缘无故停止。大多数情况下,这是因为发生了一个未被catch到的500错误,导致服务器停止工作,然后你就必须重新启动它。 forever默认使用node来启动你的服务器。

nodemon是一个npm包,可以在代码更改或服务器停止时重新启动你的服务器。

你可以通过以下方式同时使用forevernodemon:

forever start nodemon --exitcrash app.js
或者
forever start -c nodemon app.js

或者,如其他答案中所建议的,您可以使用PM2,这对于生产环境会更好!


现在似乎永远都包含了监视。使用“forever -o out.log -e err.log -w app.js”。 - vandijkstef

28

我建议使用PM2

这是在生产服务器上运行的最佳选择。

使用这种方式运行应用程序有哪些优点?

  • 易于设置和运行。
  • 如果应用程序崩溃,PM2将自动重新启动它。
  • PM2将记录未处理的异常 - 在这种情况下,记录在/home/safeuser/.pm2/logs/app-err.log文件中。
  • 通过一个命令,PM2可以确保它管理的任何应用程序在服务器重新启动时重新启动。这基本上意味着您的Node应用程序将作为服务启动。

参考:https://www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps


PM2是一个强力的Copyleft软件包,请确保不要在商业项目中使用它。 - undefined

3
这是一个使用 cron 运行脚本的示例,可以重新启动服务/执行某些自动化任务。基本上,我创建了一些需要在服务器上特定时间间隔运行的脚本。对于您的情况,您想要创建一个脚本,它将自动检查 forever.js 的状态,如果返回错误响应,则运行上面提到的 forever restartall 命令。 crontab 您可以通过在服务器上 创建新的 crontab 条目 来设置此项。至于脚本方面,我绝不是 bash 脚本大师;我制作了一个适合我的简单脚本。 下面是一个检查我的机器上服务并在其未运行时重新启动它的示例。
#!/bin/bash
zabbix_server="service zabbix-server"
zabbix_agent="service zabbix-agent"
logfile=zabbix_auto_restart.log
logfilePath=/etc/scripts/zabbix/$logfile
zabbix_server_running=0
zabbix_agent_running=0

grep_agent (){
        local retval=$(ps -ef | grep -v grep | grep zabbix_agentd | wc -l)
        echo $retval
}

grep_server (){
        local retval=$(ps -ef | grep -v grep | grep zabbix_server | wc -l)
        echo $retval
}

check_zabbix_agentd (){
        if (( $(grep_agent) <= 0 ))
        then
           sudo /etc/init.d/zabbix-agent start
           echo `date` "$zabbix_agent was stopped... Restarting" >> $logfilePath
           echo "************************************************" >> $logfilePath

           #Send email to notify that the script ran
           echo "$(date) $zabbix_agent was restarted from zabbix_restart.sh" | mutt -s "Zabbix Auto-restart Script Just Ran" <my-email>

        else
           let zabbix_agent_running=1
        fi
}

check_zabbix_server (){
        if (( $(grep_server) <= 0 ))
        then
           sudo /etc/init.d/zabbix-server start
           echo `date` "$zabbix_server was stopped... Restarting" >> $logfilePath
           echo "************************************************" >> $logfilePath

           #Send email to notify that the script ran
           echo "$(date) $zabbix_server was restarted from zabbix_restart.sh" | mutt -s "Zabbix Auto-restart Script Just Ran" evan.bechtol@ericsson.com

        else
           let zabbix_server_running=1
        fi
}

main_loop (){
        until ((zabbix_server_running == 1 && zabbix_agent_running == 1));
        do
                check_zabbix_agentd
                check_zabbix_server
                sleep 1.5
        done
}

main_loop

2

这个视频是一个很棒的node部署系列的一部分,最终在UNIX服务器上使用服务...也许对你有帮助。顺便说一下,值得观看所有四个视频... Youtube链接


1

您是否考虑过使用pm2作为替代方案。pm2具有一些非常不错的功能,例如:

  • 运行集群
  • 逐个重启集群中的实例(零停机部署)
  • 资源监控(显示实时CPU和内存使用情况)
  • 使用cli管理所有pm2进程

您还可以通过添加--restart-delay <delay>选项来控制重启。

以下是此工具的完整输出。

pm2 --help

                    -------------
Looking for a complete monitoring and management tool for PM2?
 _                             _        _            _
| | _____ _   _ _ __ ___   ___| |_ _ __(_) ___ ___  (_) ___
| |/ / _ \ | | | '_ ` _ \ / _ \ __| '__| |/ __/ __| | |/ _ \
|   <  __/ |_| | | | | | |  __/ |_| |  | | (__\__ \_| | (_) |
|_|\_\___|\__, |_| |_| |_|\___|\__|_|  |_|\___|___(_)_|\___/
     |___/

                      Features

               - Real Time Dashboard
               - CPU/Memory monitoring
               - HTTP monitoring
               - Event notification
               - Custom value monitoring
               - Real Time log display

                      Checkout

               https://keymetrics.io/

                    -------------

[PM2] Spawning PM2 daemon
[PM2] PM2 Successfully daemonized

Usage: pm2 [cmd] app

Commands:

start [options] <file|json|stdin|app_name|pm_id...>                  start and daemonize an app
deploy <file|environment>                                            deploy your json
startOrRestart <json>                                                start or restart JSON file
startOrReload <json>                                                 start or gracefully reload JSON file
startOrGracefulReload <json>                                         start or gracefully reload JSON file
stop [options] <id|name|all|json|stdin...>                           stop a process (to start it again, do pm2 restart <app>)
restart [options] <id|name|all|json|stdin...>                        restart a process
scale <app_name> <number>                                            scale up/down a process in cluster mode depending on total_number param
reload <name|all>                                                    reload processes (note that its for app using HTTP/HTTPS)
gracefulReload <name|all>                                            gracefully reload a process. Send a "shutdown" message to close all connections.
id <name>                                                            get process id by name
delete <name|id|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 <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
publish|module:publish                                               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>
interact [options] [secret_key|command] [public_key] [machine_name]  linking action to keymetrics.io - command can be stop|info|delete|restart
link [options] [secret_key|command] [public_key] [machine_name]      linking action to keymetrics.io - command can be stop|info|delete|restart
web                                                                  launch a health API on port 9615
dump                                                                 dump all processes for resurrecting them later
save                                                                 (alias) dump all processes for resurrecting them later
resurrect                                                            resurrect previously dumped processes
startup [platform]                                                   auto resurrect process at startup. [platform] = ubuntu, centos, redhat, gentoo, systemd, darwin, amazon
logrotate                                                            copy default logrotate configuration
generate                                                             generate an ecosystem.json configuration file
ecosystem                                                            generate an ecosystem.json configuration file
reset <name|id|all>                                                  reset counters for process
describe <id>                                                        describe all parameters of a process id
desc <id>                                                            (alias) describe all parameters of a process id
info <id>                                                            (alias) describe all parameters of a process id
show <id>                                                            (alias) describe all parameters of a process id
list                                                                 list all processes
ls                                                                   (alias) list all processes
l                                                                    (alias) list all processes
status                                                               (alias) list all processes
jlist                                                                list all processes in JSON format
prettylist                                                           print json in a prettified JSON
monit                                                                launch termcaps monitoring
m                                                                    (alias) launch termcaps monitoring
flush                                                                flush logs
reloadLogs                                                           reload all logs
logs [options] [id|name]                                             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
gc                                                                   force PM2 to trigger garbage collection
deepUpdate                                                           performs a deep update of PM2
*

Options:

-h, --help                           output usage information
-V, --version                        output the version number
-v --version                         get version
-s --silent                          hide all messages
-m --mini-list                       display a compacted list without formatting
-f --force                           force actions
-n --name <name>                     set a <name> for script
-i --instances <number>              launch [number] instances (for networked app)(load balanced)
-l --log [path]                      specify entire log file (error and out are both included)
-o --output <path>                   specify out log file
-e --error <path>                    specify error log file
-p --pid <pid>                       specify pid file
-k --kill-timeout <delay>            delay before sending final SIGKILL signal to process
--max-memory-restart <memory>        specify max memory amount used to autorestart (in megaoctets)
--restart-delay <delay>              specify a delay between restarts (in milliseconds)
--env <environment_name>             specify environment to get specific env variables (for JSON declaration)
-x --execute-command                 execute a program using fork system
-u --user <username>                 define user when generating startup script
--hp <home path>                     define home path when generating startup script
-c --cron <cron_pattern>             restart a running process based on a cron pattern
-w --write                           write configuration in local folder
--interpreter <interpreter>          the interpreter pm2 should use for executing app (bash, python...)
--interpreter-args <arguments>       interpret options (alias of --node-args)
--log-date-format <momentjs format>  add custom prefix timestamp to logs
--no-daemon                          run pm2 daemon in the foreground if it doesn't exist already
--skip-env                           do not refresh environmnent on restart/reload
--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
--merge-logs                         merge logs from different instances but keep error and out separated
--watch [paths]                      watch application folder for changes
--ignore-watch <folders|files>       folder/files to be ignored watching, chould be a specific name or regex - e.g. --ignore-watch="test node_modules "some scripts""
--node-args <node_args>              space delimited arguments to pass to node in cluster mode - e.g. --node-args="--debug=7001 --trace-deprecation"
--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

Basic Examples:

Start an app using all CPUs available + set a name :
$ pm2 start app.js -i 0 --name "api"

Restart the previous app launched, by name :
$ pm2 restart api

Stop the app :
$ pm2 stop api

Restart the app that is stopped :
$ pm2 restart api

Remove the app from the process list :
$ pm2 delete api

Kill daemon pm2 :
$ pm2 kill

Update pm2 :
$ npm install pm2@latest -g ; pm2 update

More examples in https://github.com/Unitech/pm2#usagefeatures

Deployment help:

$ pm2 deploy help

1
在早些时候调查此事时,我读到了有关Forever的几个问题。基于这个原因,我选择了PM2,尽管使用了数月,但我没有任何抱怨的理由。 - Carlos Jimenez Bermudez

0

问题解决了。我的 EC2 实例可用的内存不足,所以导致了问题。我将内存升级到了 2 GB,目前还没有出现崩溃。

Node 也可能会出现未捕获的异常错误,但我的主要问题是由于内存不足引起的。

希望这能帮助其他人。


6
虽然这是解决你问题的方法,但并不完全回答了所提出的问题。未来你可能会再次遇到更大的负载,而纵向扩展通常并不是解决方案。 - juz
2
你真的应该查看我上面的回答,使用pm2。你可以使用pm2 monit <yourapplication>随时查看实时内存使用情况。 - Marco
还要检查pm2选项,以防止内存泄漏问题,如果进程使用了某些内存,则自动重新启动进程。 --max-memory-restart - Marco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接