Docs / Monitoring & Logging / Writing Health Check Scripts for Your Services

Writing Health Check Scripts for Your Services

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 25 views · 2 min read

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
fi

Database 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
fi

Disk 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
done

Combined 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
done

Scheduling

Add to cron for regular checks:

# Every 5 minutes
*/5 * * * * /root/scripts/health-check.sh >> /var/log/health-check.log 2>&1

Was this article helpful?