Script to automatically start Nginx, Mariadb, PHP when Web error 502 Bad Gateway

In some cases where the server crashes, causing the Website to not work, we can use cronjob to check, if the Website returns error code 502 Bad Gateway, then restart nginx, mariadb, php7.4-fpm. Proceed as follows:

Auto Restart Nginx, Mariadb, PHP When Website Error 502 Bad Gateway

Create file 502.sh with content:

#!/bin/bash

CheckURL="https://anonyviet.com"
 
STATUS_CODE=`curl -o /dev/null -m 10 --connect-timeout 10 -s -w %{http_code} $CheckURL`
echo $STATUS_CODE
if [[ "$STATUS_CODE" == '000' || "$STATUS_CODE" == '502' ]]; then

    /usr/bin/systemctl restart nginx
    /usr/bin/systemctl restart mariadb
    /usr/bin/systemctl restart php7.4-fpm
    echo "sap web vao luc: $(date)" >> /root/a.txt
fi

Explain:

  • If curl returns error code 000 or 502 then execute 3 commands restart nginx, mariadb, php7.4-fpm
  • Also record the Log when these 3 services restart to the file a.txt

Timer every minute to run file 502.sh to check

Type command to open cronjob

EDITOR=nano crontab -e

Paste the following into the Terminal window (run the file /root/502.sh . every minute)

* * * * * bash /root/502.sh >/dev/null 2>&1

Press Ctrl+O, Enter to save and Ctrl+X to exit

Tut by An0nyViet

Leave a Reply