BASH
Robust HTTP Server Health Check with Retries
Implement a Bash script to health-check a web server's HTTP status with retry attempts, crucial for deployment verification and CI/CD pipelines.
#!/bin/bash
URL="http://localhost:3000"
MAX_RETRIES=10
RETRY_INTERVAL=5 # seconds
echo "Checking server availability at $URL..."
for i in $(seq 1 $MAX_RETRIES); do
HTTP_STATUS=$(curl -o /dev/null -s -w "%""%{http_code}""" "$URL")
if [ "$HTTP_STATUS" -eq 200 ]; then
echo "Server is up and responsive (HTTP $HTTP_STATUS)!"
exit 0
else
echo "Attempt $i/$MAX_RETRIES: Server returned HTTP $HTTP_STATUS. Retrying in $RETRY_INTERVAL seconds..."
sleep "$RETRY_INTERVAL"
fi
done
echo "Error: Server did not become responsive after $MAX_RETRIES attempts."
exit 1
How it works: This script performs a health check on a web server by repeatedly querying a specified URL using `curl`. It includes a retry mechanism with a defined number of `MAX_RETRIES` and a `RETRY_INTERVAL`. The script checks the HTTP status code returned; it exits successfully if a 200 OK status is received, otherwise it retries. If the server doesn't become responsive after all retries, the script exits with an error.