BASH

Basic Health Check for a Web Service URL

Perform a simple yet effective health check on a web service URL, verifying its reachability and successful HTTP status, with optional retries.

#!/bin/bash

# Configuration
URL="https://your-web-service.com/health"
EXPECTED_STATUS_CODE_START=200
EXPECTED_STATUS_CODE_END=299
MAX_RETRIES=3
RETRY_DELAY_SECONDS=5

function check_url() {
  local url="$1"
  local attempt=1
  while [ $attempt -le $MAX_RETRIES ]; do
    echo "Attempt $attempt of $MAX_RETRIES: Checking URL $url..."
    # -s: silent, -o /dev/null: discard output, -w '%{http_code}': print http code
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$url")
    
    if (( HTTP_CODE >= EXPECTED_STATUS_CODE_START && HTTP_CODE <= EXPECTED_STATUS_CODE_END )); then
      echo "Success: URL $url returned HTTP $HTTP_CODE"
      return 0 # Success
    else
      echo "Warning: URL $url returned HTTP $HTTP_CODE. Retrying in $RETRY_DELAY_SECONDS seconds..."
      sleep $RETRY_DELAY_SECONDS
    fi
    attempt=$((attempt + 1))
  done
  echo "Error: URL $url failed after $MAX_RETRIES attempts (last HTTP code: $HTTP_CODE)"
  return 1 # Failure
}

# Execute the health check
if check_url "$URL"; then
  echo "Web service is healthy."
  exit 0
else
  echo "Web service is UNHEALTHY."
  exit 1
fi
How it works: This script performs a basic health check on a specified web service URL. It uses `curl` to make a request and retrieves only the HTTP status code, discarding the actual response body. The script then checks if the returned status code falls within the successful range (200-299). If the initial check fails, it retries a configurable number of times with a delay. This is useful for monitoring service availability, integration tests, or as part of a CI/CD pipeline.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs