BASH

Perform Basic HTTP Health Check with Curl

Create a bash script to perform basic health checks on web services or URLs using `curl`, verifying HTTP status codes and response times for service availability.

#!/bin/bash

# Define the URL to check
TARGET_URL="http://localhost:3000" # Replace with your target URL
EXPECTED_STATUS=200 # Expected HTTP status code
TIMEOUT=5 # Timeout in seconds

echo "Performing HTTP health check for $TARGET_URL..."

# Use curl to get HTTP status code and response time
HTTP_STATUS=$(curl -o /dev/null -s -w "%{{http_code}}" --max-time "$TIMEOUT" "$TARGET_URL")

# You can also get other info like total time:
# TOTAL_TIME=$(curl -o /dev/null -s -w "%{{time_total}}" --max-time "$TIMEOUT" "$TARGET_URL")
# echo "Response Time: ${TOTAL_TIME}s"

if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
  echo "Success: $TARGET_URL is reachable and returned status $HTTP_STATUS."
  exit 0
else
  echo "Failure: $TARGET_URL returned status $HTTP_STATUS (Expected: $EXPECTED_STATUS) or timed out."
  exit 1
fi
How it works: This script utilizes `curl` to perform a basic HTTP health check on a specified `TARGET_URL`. It retrieves the HTTP status code and checks if it matches the `EXPECTED_STATUS`. It also sets a `TIMEOUT` and provides an exit status indicating success or failure, useful for automation or monitoring.

Need help integrating this into your project?

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

Hire DigitalCodeLabs