BudiBadu Logo
Samplebadu

Bash by Example: Service Health Check

Bash 5.0+

Verifying that a web service is responding to HTTP requests using curl or wget for health checks, implementing application-level monitoring beyond port checks, validating HTTP response codes for service availability, testing web service endpoints automatically, and integrating health checks into deployment pipelines.

Code

#!/bin/bash

URL="http://google.com"
TIMEOUT=5

echo "Checking health of $URL..."

# curl flags:
# -s : Silent (no progress bar)
# -o /dev/null : Discard the body content
# -w "%{http_code}" : Write ONLY the HTTP status code to stdout
status_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout $TIMEOUT "$URL")

if [ "$status_code" -eq 200 ]; then
    echo "Service is UP (Status: $status_code)"
    exit 0
else
    echo "Service is DOWN or Unhealthy (Status: $status_code)"
    # In a real script, you might restart the service here
    # systemctl restart apache2
    exit 1
fi

Explanation

Just because a process is running doesn't mean it's working. A web server process might be active but stuck in a deadlock, returning 500 errors, or refusing connections. A "Health Check" tests the service from the outside, mimicking a real user request to verify functionality.

The curl command is the Swiss Army knife for HTTP interactions. In this script, we use it to send a request to a URL and inspect the HTTP Status Code. A code of 200 means "OK". Codes like 404 (Not Found) or 500 (Server Error) indicate problems.

We use specific flags to make curl suitable for scripting: -s makes it silent, -o /dev/null throws away the actual HTML page (since we only care about the status), and -w "%{http_code}" forces it to output only the status number. This gives us a clean integer we can check in an if statement.

Code Breakdown

12
-w "%{http_code}" is a powerful formatting feature of curl. It allows you to extract specific metadata about the transfer (like time_total, size_download, etc.) without parsing text.
12
--connect-timeout prevents the script from hanging indefinitely if the server is unreachable (e.g., network cable unplugged). It forces a failure after 5 seconds.