BASH
Basic Web Service Health Check with cURL
Perform a simple health check on a web service endpoint using cURL, verifying its HTTP status code and response time, useful for monitoring.
#!/bin/bash
SERVICE_URL="http://localhost:3000/health"
EXPECTED_STATUS=200
TIMEOUT_SECONDS=5
# Use curl to get HTTP status code and total time
# -o /dev/null: Discard response body
# -s: Silent mode (don't show progress meter or error messages)
# -w "%{
http_code}
%{time_total}
": Custom output format for status code and total time
# -m $TIMEOUT_SECONDS: Set maximum time for the operation
HEALTH_CHECK_OUTPUT=$(curl -o /dev/null -s -w "%{
http_code}
%{time_total}
" -m "$TIMEOUT_SECONDS" "$SERVICE_URL")
HTTP_STATUS=$(echo "$HEALTH_CHECK_OUTPUT" | head -n 1)
RESPONSE_TIME=$(echo "$HEALTH_CHECK_OUTPUT" | tail -n 1)
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
echo "Service at $SERVICE_URL is healthy. Status: $HTTP_STATUS, Response time: ${RESPONSE_TIME}s"
exit 0
else
echo "Service at $SERVICE_URL is UNHEALTHY. Expected status $EXPECTED_STATUS, Got: $HTTP_STATUS, Response time: ${RESPONSE_TIME}s"
exit 1
fi
How it works: This script performs a basic health check on a specified web service URL using `cURL`. It retrieves the HTTP status code and total response time, comparing the status code against an `EXPECTED_STATUS`. If the status matches and the request completes within the timeout, the service is considered healthy; otherwise, it reports an unhealthy status. This is useful for simple uptime monitoring and integration into automated checks.