VPS Server with little memory is it very important to set up crontab job to automatically restart VPS Server on low memory based on condition. Check how much memory is left on the VPS Server, if 100M memory left then reboot the VPS Server.
Write bash script to checks how much memory is left and reboot the VPS.
#vim restartmemorylow
Below is script for CentOS, for Debian 7/8 find at bottom of this page
#!/bin/bash mem=$(free -m | awk '/Mem:/{print $4}') (( mem <= 100 )) && /sbin/shutdown -r now
We also can Swap memory, if less than 100M then reboot VPS Server
#vim restartswapmemorylow
#!/bin/bash swapmem=$(free -m | awk '/Swap:/{print $4}') (( swapmem <= 100 )) && /sbin/shutdown -r now
Make the script executable
#chmod +x restartmemorylow #chmod +x restartswapmemorylow
Add script to the to crontab (make sure path/to/the/script correct)
crontab -u root -e
Check memory low every week At 01:00 on Sunday (https://crontab.guru)
0 1 * * 0 /restartmemorylow 0 1 * * 0 /restartswapmemorylow
Error occurred and how to solved
Check error by check current mail with following command
tail -f /var/spool/mail/root
If crontab command not found, Install cron with following command
#crontab -u root -e -bash: crontab: command not found #yum install vixie-cron crontabs #chkconfig crond on #service crond start #chkconfig --list | grep crond
Low memory script and install cron on Debian 7 / 8
#vim restartmemorylow
#!/bin/bash mem=$(cat /proc/meminfo | egrep "^MemFree" |awk '{print $2}') if (( mem <= 51200 )); then echo "Memory lower than or 10%, so we kill and restart"; /sbin/shutdown -r now else echo "Memory is fine" fi
Make the script executable
#chmod +x restartmemorylow
#apt-get install cron
For all cron jobs that should be executed under a user’s account, you should use crontab -e. For system jobs, you should add a file under /etc/cron.d, if that exists; under /etc/cron.{hourly|daily|weekly|monthly} (but those must not be named like a package name!), if that fits your purpose; or add a line to /etc/crontab. But be aware that /etc/crontab might be overwritten with a system update.
Insert
#crontab -u root -e 0 1 * * 0 root /restartmemorylow
Enable cron log on Debian
#vim /etc/rsyslog.conf
In the file, you will find the following line: #cron.* -/var/log/cron
Uncomment the line (remove the #) and save the rsyslog.conf file
cron.* -/var/log/cron
#service rsyslog restart
After restarting the rsyslog daemon, crontab log entries will appear in the /var/log/cron.log file.