Service Health Check Script with Notifications
Beginner10 min
Build a bash script that monitors service endpoints, checks response codes and latency, and sends alerts when services are down.
Prerequisites
- -Bash and curl installed
- -Services or URLs to monitor
Steps
1
Check a single endpoint
Use curl to verify a service returns HTTP 200 and measure response time.
$ curl -s -o /dev/null -w '%{http_code} %{time_total}s' http://localhost:3000/health
-s silences progress, -o /dev/null discards body, -w prints status code and timing.
2
Create a multi-service health check script
Loop through a list of endpoints and check each one.
$ cat > healthcheck.sh << 'EOF'
#!/usr/bin/env bash
set -euo pipefail
ENDPOINTS=(
"http://localhost:3000/health"
"http://localhost:3001/api/health"
"https://api.example.com/status"
)
for url in "${ENDPOINTS[@]}"; do
HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$url" || echo "000")
if [[ "$HTTP_CODE" -eq 200 ]]; then
echo "[OK] $url ($HTTP_CODE)"
else
echo "[FAIL] $url ($HTTP_CODE)" >&2
fi
done
EOF
chmod +x healthcheck.sh
3
Add response time monitoring
Track response times and flag slow endpoints above a threshold.
$ echo 'RESPONSE_TIME=$(curl -s -o /dev/null -w "%{time_total}" --max-time 10 "$url")' && echo 'if (( $(echo "$RESPONSE_TIME > 2.0" | bc -l) )); then echo "[SLOW] $url (${RESPONSE_TIME}s)"; fi'
4
Add webhook notification on failure
Send an alert to Slack or Discord when a health check fails.
$ echo 'curl -s -X POST -H "Content-Type: application/json" -d "{\"text\": \"ALERT: $url returned $HTTP_CODE\"}" "$WEBHOOK_URL"'
Store webhook URLs in environment variables, not in the script. Never commit secrets to version control.
Full Script
FAQ
Discussion
Loading comments...