Script to restart server if load increases above a given limit

Script to restart a server automatically if it’s load increases above a limit :

#!/usr/bin/ bash
LOAD=`uptime |awk '{print $NF}'`
LOADCOMP=`echo $LOAD \> 15 |bc -l`
if [ $LOADCOMP -eq 1 ]
then /sbin/shutdown -r 0
fi

 

Note:  Here 15 defines the server load, you can adjust as per your need.

  • Write this code in a file (eg. nano restartscript.sh) and paste the code.
  • The file should have extension .sh. After saving the script, make it executable by running the following command :

 

chmod 777 restartscript.sh

  • Now we need to add this script to cron which will run every 2 minutes
  • Type crontab -e to open the cron input file.
  • Enter the following code to run the script we just created

 

*/2 * * * * cd /path/to/file && sh ./restartscript.sh > /var/log/cronlogfile.log 2>&1

 

Note :

You need to replace /path/to/file with the path directory you have saved the file.

 

To check if cron is added successfully run crontab -l to list all the crons.

 

Now, whenever the specific server load will go beyond the given limit (i.e 10 in our case), the server / VPS will reboot. Though this is a temporary solution if you are facing sudden/abnormal spikes in your server and restarting fixes the same. On a longer run, you need to debug the same and resolve the main issue which causes the load spike.

 

Was this answer helpful? 0 Users Found This Useful (0 Votes)