← Back to all snippets
BASH

Check and Wait for a TCP Port to Become Available

Create a robust Bash script to repeatedly check if a specific TCP port on a host is open, useful for ensuring service dependencies are ready in CI/CD pipelines.

#!/bin/bash

HOST="localhost"
PORT="8080"
TIMEOUT=5 # seconds
RETRIES=12 # number of retries, total wait time = RETRIES * TIMEOUT

echo "Waiting for $HOST:$PORT to be available..."

for i in $(seq 1 $RETRIES); do
    # Use netcat (nc) to check if the port is open
    # -z: zero-I/O mode (just scan for listening daemons)
    # -w 1: timeout for connection (1 second)
    nc -z -w 1 "$HOST" "$PORT" >/dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "$HOST:$PORT is available!"
        exit 0
    else
        echo "Attempt $i/$RETRIES: $HOST:$PORT not yet available. Waiting $TIMEOUT seconds..."
        sleep "$TIMEOUT"
    fi
done

echo "Error: $HOST:$PORT did not become available after $RETRIES attempts."
exit 1
How it works: This script monitors a specific TCP port on a given host, waiting for it to become available. It uses `netcat` (`nc`) in zero-I/O mode with a connection timeout to check the port. The script retries multiple times with a configurable delay, making it useful for orchestrating services or ensuring dependencies are ready in deployment pipelines.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs