Reemus Icon

Check & Wait For PostgreSQL To Become Ready

👍🔥❤️😂😢😕
views
comments

Perhaps you want to run some migrations or execute some queries after starting your Postgres instance. To avoid errors, you are probably thinking you should wait for your DB to be ready.

Here's the approaches you could take:

  • sleep $DURATION - Naive and error prone
  • psql - The native CLI to connect and execute statements against the database
  • pg_isready - Dedicated and native CLI to validate Postgres is up and ready

Using pg_isready has a few benefits:

  • It doesn't require a password as it does not actually connect to the database
  • It simply checks that a valid connection can be established

To check that a postgres instance is ready:

pg_isready -h "$HOST" -p "$PORT" -d "$DB_NAME" -U "$USER"
bash-icon

The command can exit with 3 possible exit codes:

  • 0 - success, the instance is accepting connections
  • 1 - error, the instance is starting up and not ready yet
  • 2 - error, a connection could not be established

Using this, if you want to check and wait for a postgres instance to become ready.

RETRY_COUNT=0
RETRY_MAX=10
RETRY_INTERVAL=3
while ! pg_isready -h "$HOST" -p "$PORT" -d "$DB_NAME" -U "$USER" 2>/dev/null; do
  RETRY_COUNT=$(($RETRY_COUNT + 1))
  if [ $RETRY_COUNT -ge $RETRY_MAX ]; then
    echo "PostgreSQL not ready after ${RETRY_MAX} attempts. Exiting."
    exit 1
  fi
  echo "Waiting for PostgreSQL to be ready... Attempt: ${RETRY_COUNT}"
  sleep "${RETRY_INTERVAL}"
done
bash-icon
👍🔥❤️😂😢😕

Comments

...

Your name will be displayed publicly

Loading comments...