BASH
Wait for a Specific Port to Become Available
Ensure dependent services start in the correct order by pausing script execution until a specified network port is listening, preventing connection errors.
#!/bin/bash
HOST="localhost"
PORT="8080" # The port to wait for
TIMEOUT=60 # Max time to wait in seconds
INTERVAL=2 # Check interval in seconds
echo "Waiting for $HOST:$PORT to become available (timeout: ${TIMEOUT}s)..."
start_time=$(date +%s)
while ! nc -z "$HOST" "$PORT" >/dev/null 2>&1; do
elapsed_time=$(($(date +%s) - start_time))
if (( elapsed_time >= TIMEOUT )); then
echo "Error: Timeout reached ($TIMEOUT seconds). Port $PORT on $HOST not available."
exit 1
fi
echo "Port $PORT on $HOST not yet available. Retrying in $INTERVAL seconds..."
sleep "$INTERVAL"
done
echo "Port $PORT on $HOST is now available!"
exit 0
How it works: This script continuously checks if a specified network port on a given host is listening using `nc` (netcat). It waits for the port to become available, retrying at defined intervals, until either the port is open or a timeout is reached. This is invaluable in CI/CD pipelines or deployment scripts where you need to ensure a service (like a database or web application) is fully started and listening before proceeding with subsequent steps.