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.

All Real-World Interview questions Roadmap: Interview readiness

More on Bash scripting tasks