Write a script that waits for a TCP port (e.g. a database) to become reachable before starting the app.
AdvancedHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
HOST="${DB_HOST:-db}"; PORT="${DB_PORT:-5432}"; TIMEOUT=60
for ((i = 0; i < TIMEOUT; i++)); do
if (echo > "/dev/tcp/$HOST/$PORT") 2>/dev/null; then
echo "$HOST:$PORT is up"
exec "$@"
fi
sleep 1
done
echo "Gave up waiting for $HOST:$PORT" >&2
exit 1
Use it as ENTRYPOINT ["/wait-for.sh", "python", "app.py"].
Key trick → /dev/tcp/host/port is a Bash built-in pseudo-device, so no nc is needed in the image. exec "$@" replaces the shell so the app becomes PID 1 and receives signals.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate