Why Health Checks?
Health check scripts verify that your services are not just running but actually functional. A web server might be running but returning 500 errors — a simple process check wouldn't catch that.
HTTP Health Check
#!/bin/bash
URL="https://example.com"
EXPECTED_CODE=200
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$URL")
if [ "$HTTP_CODE" != "$EXPECTED_CODE" ]; then
echo "ALERT: $URL returned $HTTP_CODE (expected $EXPECTED_CODE)" | \
mail -s "Health Check Failed: $URL" admin@example.com
fiDatabase Health Check
#!/bin/bash
if ! mysqladmin ping -u healthcheck --silent 2>/dev/null; then
echo "ALERT: MySQL is not responding" | \
mail -s "MySQL Health Check Failed" admin@example.com
systemctl restart mariadb
fiDisk Space Check
#!/bin/bash
THRESHOLD=85
df -H | awk 'NR>1 {gsub(/%/,"",$5); if($5 > '$THRESHOLD') print $6 " is " $5 "% full"}' | \
while read line; do
echo "ALERT: $line" | mail -s "Disk Space Warning" admin@example.com
doneCombined Service Check
#!/bin/bash
SERVICES="nginx mariadb redis php8.2-fpm"
for svc in $SERVICES; do
if ! systemctl is-active --quiet "$svc"; then
echo "$svc is down — attempting restart"
systemctl restart "$svc"
echo "Service $svc was down and restarted at $(date)" | \
mail -s "Service Restart: $svc" admin@example.com
fi
doneScheduling
Add to cron for regular checks:
# Every 5 minutes
*/5 * * * * /root/scripts/health-check.sh >> /var/log/health-check.log 2>&1