Bash

Wait For Docker Container to Be Healthy

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
docker-compose entrypoints often need to wait for a sibling service (DB, cache) to be healthy before starting work. Poll the health-check status until healthy or timeout.
Bash
Raw
wait_healthy() {
    local container="$1" timeout="${2:-60}"
    local start; start=$(date +%s)
    while true; do
        local status
        status="$(docker inspect -f '{{.State.Health.Status}}' "$container" 2>/dev/null || echo "missing")"
        case "$status" in
            healthy)  echo "$container is healthy"; return 0 ;;
            unhealthy) echo "$container is unhealthy" >&2; return 1 ;;
        esac
        if (( $(date +%s) - start > timeout )); then
            echo "Timeout waiting for $container after ${timeout}s (last: $status)" >&2
            return 1
        fi
        sleep 1
    done
}

wait_healthy app-db 60 && rails db:migrate
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.