From 1d146dd0d47e9e998e443e4f82ef1ad241a80fe2 Mon Sep 17 00:00:00 2001 From: leo <426742@gmail.com> Date: Sun, 18 Aug 2024 08:37:27 +0500 Subject: [PATCH] add checking of ready for PostgreSQL container --- init-db.sh | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/init-db.sh b/init-db.sh index 25b1fc1..74db649 100644 --- a/init-db.sh +++ b/init-db.sh @@ -15,13 +15,39 @@ set -e export DEBIAN_FRONTEND=noninteractive +PG_CONTAINER=postgres CREATE_DB_NAME=$1 CREATE_DB_PASSWORD=$2 : "${POSTGRES_USER:?}" : "${POSTGRES_DB:?}" -sudo docker exec -i postgres psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" <<-EOSQL +# Function to check container status: +check_container_state() { + state=$(sudo docker inspect -f '{{.State.Health.Status}}' "$PG_CONTAINER" 2>/dev/null) + + if [ "$state" = "healthy" ]; then + return 0 + fi + + state=$(sudo docker inspect -f '{{.State.Status}}' "$PG_CONTAINER" 2>/dev/null) + + if [ "$state" = "running" ]; then + return 0 + fi + + return 1 +} + +echo "Waiting for PostgreSQL container to start..." +while ! check_container_state; do + echo "Waiting for PostgreSQL container to be ready..." + sleep 5 +done + +echo "PostgreSQL container is ready. Init DB..." + +sudo docker exec -i $PG_CONTAINER psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" <<-EOSQL CREATE USER "$CREATE_DB_NAME" WITH ENCRYPTED PASSWORD '$CREATE_DB_PASSWORD'; CREATE DATABASE "$CREATE_DB_NAME"; GRANT ALL PRIVILEGES ON DATABASE "$CREATE_DB_NAME" TO "$CREATE_DB_NAME";