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

bashsnippet
22 lines
#!/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

How the snippet works

Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.

The work is delegated to sleep and wait_for_ready, chained so each stage’s output feeds the next.

A helper function (wait_for_ready) keeps the repeated logic out of the main flow.

The script leans on parameter expansion 5 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

The key statements, annotated

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

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`sleep`, `wait_for_ready` must be available on the PATH environment variable; everything else is shell built-in syntax.