Script to automatically restart service when website error 502 Bad Gateway
Step 1: Create a file: service_checker.conf
sudo mkdir /etc/auto
cd /etc/auto
sudo nano service_checker.conf
add line as below
https://itricks.me|odooitricks
https://domain.com|odooxxx
Notice the "|" character.
sudo chmod +x service_checker.conf
Step 2: Create file: check_and_restart.sh
----> Requiment: curl
Install curl: apt install curl or snap install curl
sudo nano check_and_restart.sh
#!/bin/bash
# path to config file
CONFIG_FILE="/etc/auto/service_checker.conf"
echo "$(date) : start check" >> /var/log/auto_check_restart.log
# Read and check
while IFS='|' read -r url service; do
# check status for url
response=$(curl -s -o /dev/null -w "%{http_code}" $url)
echo "$url" >> /var/log/auto_check_restart.log
echo "$service" >> /var/log/auto_check_restart.log
echo "$response" >> /var/log/auto_check_restart.log
# check error 502
if [ $response -eq 502 ]; then
# restart service
systemctl restart "$service"
echo "$(date) : Detected 502 error for $service " >> /var/log/auto_check_restart.log
fi
# sleep 10 seconds
sleep 10
done < "$CONFIG_FILE"
sudo chmod +x check_and_restart.sh
* if [ $response -ne 200 ]; then
"-ne" is "!="
Step 3: Crontab
crontab -e
#Run command every 30 minutes
*/30 * * * * /etc/auto/check_and_restart.sh
#Run command every 1 minutes
* * * * * /etc/auto/check_and_restart.sh
#Run command every week
0 0 * * 0 /etc/auto/check_and_restart.sh
#every day
0 0 * * * /etc/auto/check_and_restart.sh
#every hour
0 * * * * /etc/auto/check_and_restart.sh
Done!
Một cách khác tin gọn hơn
#!/bin/bash
# path to config file
CONFIG_FILE="/etc/auto/service_checker.conf"
echo "$(date) : start check" >> /var/log/auto_check_restart.log
# Read and check
while IFS='|' read -r url service; do
# check status for url
response=$(curl -s -o /dev/null -w "%{http_code}" $url)
echo "Time: $(date): " >> /var/log/auto_check_restart.log
echo "$url" >> /var/log/auto_check_restart.log
echo "$service" >> /var/log/auto_check_restart.log
echo "$response" >> /var/log/auto_check_restart.log
# check error 502
#if [ $response -eq 502 ]; then
#check nếu k phải trả về mã 200 thì restart
if [ $response -ne 200 ]; then
# restart service
systemctl restart "$service"
echo "$(date) : Detected error for $service " >> /var/log/auto_check_restart.log
fi
# sleep 10 seconds
sleep 10
done < "$CONFIG_FILE"