Node JS auto restart all forever JS process when server goes down / crashes

前端 未结 6 913
眼角桃花
眼角桃花 2021-02-07 05:37

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

I use this command

forever start index.js

However, I notice that

6条回答
  •  时光说笑
    2021-02-07 06:05

    So this is an example of using cronto run scripts that can restart service/perform some automated task. Basically, I created some scripts that I need to run at certain time intervals on my server. For your case, you want to make a script that will automatically check the state of your forever.js and if it returns a bad response, run the forever restartall command that you mention above.

    You can set this up by creating a new crontab entry on the server. As far as the script goes, I'm by no means a bash script guru; I made a simple script that works for me. Here is an example of checking a service on my machine, restarting it if it is not running.

    #!/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" 
    
            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
    

提交回复
热议问题