Wait for a Service to Become Ready

Poll a health endpoint until a dependency is ready or a timeout elapses, preventing a start-up script from racing ahead of its services.

BashResilience

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

wait_for_ready() {
  local url="${1:?url required}"
  local timeout="${2:-60}"
  local elapsed=0

  while (( elapsed < timeout )); do
    if curl --fail --silent --output /dev/null "${url}"; then
      echo "service ready after ${elapsed}s"
      return 0
    fi
    sleep 2
    elapsed=$(( elapsed + 2 ))
  done

  echo "service did not become ready within ${timeout}s" >&2
  return 1
}

wait_for_ready "http://localhost:8080/healthz" 30