Bash

Wait For Service With Timeout

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Block until a TCP port accepts connections, with a deadline. Used everywhere in docker-compose entrypoints — wait for the DB to be ready before running the app.
Bash
Raw
wait_for() {
    local host="$1" port="$2" timeout="${3:-60}"
    local start; start=$(date +%s)
    until timeout 1 bash -c "echo > /dev/tcp/$host/$port" 2>/dev/null; do
        if (( $(date +%s) - start > timeout )); then
            echo "Timed out waiting for $host:$port after $timeout s" >&2
            return 1
        fi
        sleep 1
    done
    echo "✓ $host:$port reachable after $(( $(date +%s) - start ))s"
}

# Wait for Postgres to come up, then run migration
wait_for db 5432 30 && rails db:migrate
Tags

Save your own code snippets

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