The endpoint is listening, yet monitoring keeps reporting a false healthy state: requests are redirected to a login page, the proxy returns a generic home page, or the response body explicitly says the service is not ready. HTTP health checks on a dedicated server must answer three separate questions: did the transfer complete, does the status code meet the agreed requirements, and does the response body demonstrate that the intended service is available? Checking only that a process exists, or searching for an “ok”, can easily miss failures.
The following example uses Bash, curl and Python 3 on Debian 12 to build a check whose failure detection can also be tested. It does not change firewall rules, restart the application or expose a test service to the public internet.
1. Define the readiness contract first
Check the application’s readiness endpoint, not its home page. In this example, a successful response must meet all of these conditions: the HTTP status is 200, the body is a JSON object, service equals orders, and ready is the boolean value true. The service name helps detect incorrect proxy routing; checking the boolean type rejects the string "true".
The connection timeout is set to 2 seconds and the total request timeout to 5 seconds. These are demonstration settings, not a promise about application response times. Production values should reflect the endpoint’s normal response time and the time budget for detecting failures. The total timeout must cover both connection establishment and reading the response body.
A liveness check answers “can the process still respond?”, while a readiness check answers “is it ready to accept application requests?”. Do not put every external dependency into a liveness check: a dependency failure could otherwise trigger a pointless restart loop.
The readiness endpoint should be lightweight, have no write side effects and return only the fields needed. It must not expose passwords, connection strings or internal stack traces. Dependency checks also need their own timeouts so that a single probe cannot occupy a worker thread indefinitely.
2. Evaluate transport, status and body separately
Save the following as health-check.sh and run it with bash health-check.sh URL. The script deliberately avoids automatic retries so that a single check does not accumulate multiple waiting periods. Let the surrounding monitoring system count consecutive failures.
#!/usr/bin/env bash
set -u
umask 077
url=${1:?Usage: health-check.sh URL}
work=$(mktemp -d) || exit 1
trap 'rm -rf -- "$work"' EXIT
status=$(curl --silent --show-error \
--noproxy '*' \
--connect-timeout 2 \
--max-time 5 \
--max-filesize 65536 \
--output "$work/body" \
--write-out '%{http_code}' \
"$url")
rc=$?
if [ "$rc" -ne 0 ]; then
printf 'FAIL transport=%s\n' "$rc" >&2
exit 1
fi
if [ "$status" != 200 ]; then
printf 'FAIL http=%s\n' "$status" >&2
exit 1
fi
if ! python3 - "$work/body" <<'PY'
import json
import sys
try:
with open(sys.argv[1], encoding="utf-8") as stream:
data = json.load(stream)
valid = (
isinstance(data, dict)
and data.get("service") == "orders"
and data.get("ready") is True
)
except (OSError, ValueError):
valid = False
sys.exit(0 if valid else 1)
PY
then
printf 'FAIL response-contract\n' >&2
exit 1
fi
printf 'OK\n'
By default, curl does not map every HTTP error status to a nonzero exit code, so the script checks the status separately. It also omits -L: a 302 redirect is itself a contract failure. Following it and treating the login page’s 200 response as success would defeat the check.
--noproxy '*' explicitly bypasses proxies configured in the environment and is suitable for probes that connect directly to the target. If the production network requires a proxy, create a separate check for that proxy path rather than copying this option unchanged. The body size limit is an additional safeguard, not a replacement for the total timeout. For responses without a declared length, verify how the limit behaves with the installed curl version.
umask restricts access to the temporary directory, and the response body is deleted on exit. Failure output contains only the failure category, not the response content, to avoid sending application data to alert logs.
3. Prove the failure paths with a local test fixture
One successful request is not enough to validate the script. Save the following as health-fixture.py and run python3 health-fixture.py in a separate terminal. It binds only to the loopback address. Port 18080 is the test port used in this article, not a default port for any service.
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/redirect":
self.send_response(302)
self.send_header("Location", "/ready")
self.send_header("Content-Length", "0")
self.end_headers()
return
if self.path == "/slow":
time.sleep(7)
payload = {
"service": "orders",
"ready": self.path != "/wrong"
}
body = json.dumps(payload).encode()
status = 200 if self.path in (
"/ready", "/wrong", "/slow"
) else 503
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass
def log_message(self, format, *args):
pass
ThreadingHTTPServer(("127.0.0.1", 18080), Handler).serve_forever()
In another terminal, run each case and read the exit code from each check:
for path in ready redirect wrong slow unavailable; do
bash health-check.sh "http://127.0.0.1:18080/$path"
printf '%s exit=%s\n' "$path" "$?"
done
Only ready should return zero. redirect should be classified as a status error, wrong as a response body error, and slow as a transport timeout. unavailable should fail because of its 503 status. The fixture is not an application implementation: even if an unknown path returns apparently correct fields, it must not pass the status check.
After stopping the fixture, request /ready again. The check must return a nonzero exit code because the connection fails. Then use Ctrl+C to stop any test processes still running; do not register the fixture as a persistent service.
4. Separate local checks from access-path checks
A successful request over the loopback address proves only that the local application path works. It does not establish that the reverse proxy, TLS or external access is working. Keep two independent checks: a direct local connection to the application, and the complete path through the proxy at the actual entry point. Both should use the same application contract, but their results must be recorded separately.
Collect evidence at the failing layer
If the local check passes but the entry-point check fails, first verify proxy routing, the entry point’s certificate and the upstream address. If both paths fail, inspect the application logs and dependency status. A transport timeout cannot be attributed directly to bandwidth, nor can a 200 response with an incorrect body be attributed directly to the network.
Production HTTPS checks must retain certificate validation. Do not use -k to turn certificate errors into successful checks. For protected endpoints, use dedicated credentials with the minimum required privileges, and keep tokens out of URL query strings and support ticket text. Check targets must come from controlled configuration, not arbitrary addresses submitted by external users.
5. Validate failure cases and recovery before deployment
Before deployment, record the script version, target path, expected fields, timeout settings and failure categories. Rerun the fixture whenever the check rules change. Otherwise, a field rename or script refactor could reduce monitoring to “any response means healthy” again.
Validation must cover at least the following:
- A ready service returns zero; a response body with the wrong service name fails.
- 302, 503 and invalid JSON all produce nonzero exit codes.
- The check terminates after a timeout without leaving an ever-growing number of child processes.
- Once the fault is resolved, the next check succeeds without reading the previous response body.
- Monitoring actually reads the script’s exit code rather than merely matching standard output.
- Alerts and logs do not retain response bodies or authentication information.
A failed health check should not trigger an unconditional restart. First define a reasonable consecutive-failure threshold and preserve diagnostic evidence, then decide whether automatic recovery is appropriate. The final deliverable is not a curl command, but a check contract that demonstrates all three outcomes: healthy responses pass, faulty responses are rejected, and recovery is recognized.
Frequently asked questions
Does a zero curl exit code prove that a service is healthy?
No. By default, curl can return zero after completing a transfer even when the HTTP status indicates an error. Validate the transfer result, expected HTTP status and application response fields separately.
Should a health check follow redirects automatically?
Readiness checks generally should not. A redirected login page can return a successful status and conceal the original endpoint failure. Check the intended endpoint directly against its status and body contract.
NodeAMD EPYC 7543P dedicated server, from $439/month