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 with content:


STATUS_CODE=`curl -o /dev/null -m 10 --connect-timeout 10 -s -w %{http_code} $CheckURL`
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


  • 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 to check

Type command to open cronjob

EDITOR=nano crontab -e

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

* * * * * bash /root/ >/dev/null 2>&1

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

Tut by An0nyViet

Leave a Reply