Skip to content

Instantly share code, notes, and snippets.

@JonathonReinhart
Created February 11, 2022 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathonReinhart/d9363715d09fbdba5fe170c8d3ca088c to your computer and use it in GitHub Desktop.
Save JonathonReinhart/d9363715d09fbdba5fe170c8d3ca088c to your computer and use it in GitHub Desktop.
Wait for service to accept connections, using bash /dev/tcp
#!/bin/bash
host="127.0.0.1"
port="13337"
maxwait=5
dur=0
while true; do
( echo -n "" > /dev/tcp/$host/$port ) 2>/dev/null
if [[ $? -eq 0 ]]; then
break
fi
if [[ $dur -eq $maxwait ]]; then
echo "Error: Service $host:$port not ready after max $maxwait seconds"
exit 1
fi
echo "Waiting for service $host:$port to accept connections... ($dur sec)"
sleep 1
dur=$((dur+1))
done
echo "Service $host:$port is ready after $dur seconds"
@JonathonReinhart
Copy link
Author

This uses bash's /dev/tcp emulation to wait for a service to accept connections.

This might be useful for a startup/entrypoint script in a Docker image (e.g. wait for a database to be ready).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment