Test postgres db connection before first init.

This commit is contained in:
sepehr 2024-12-16 20:02:04 +03:00
parent d1ccb81b16
commit 73236c342d
3 changed files with 64 additions and 11 deletions

View file

@ -31,6 +31,8 @@ COPY server-conf.json /conf/
ARG AM_I_IN_A_DOCKER_CONTAINER=Yes ARG AM_I_IN_A_DOCKER_CONTAINER=Yes
COPY init.sh /app/ COPY init.sh /app/
COPY initpy.py /app/ COPY initpy.py /app/
COPY testdb.py /app/
RUN chmod +x /app/init.sh RUN chmod +x /app/init.sh
# background spooler dir # background spooler dir

View file

@ -8,9 +8,22 @@ else
fi fi
# First Check if db is ready and accepting connections
python3 /app/testdb.py
# Check if the Python script ran successfully
if [ $? -ne 0 ]; then
echo "An error occurred while executing the SQL commands."
exit 1
else
echo "Good News! Database is Running. :)"
fi
CONTAINER_ALREADY_STARTED="CONTAINER_ALREADY_STARTED_PLACEHOLDER" CONTAINER_ALREADY_STARTED="CONTAINER_ALREADY_STARTED_PLACEHOLDER"
if [ ! -e $CONTAINER_ALREADY_STARTED ]; then if [ ! -e $CONTAINER_ALREADY_STARTED ]; then
echo "-- Initializing the mikroman for first run --" echo "-- Initializing the mikroman for first run --"
# YOUR_JUST_ONCE_LOGIC_HERE # YOUR_JUST_ONCE_LOGIC_HERE
cd /app && export PYTHONPATH=/app/py && export PYSRV_CONFIG_PATH=/conf/server-conf.json && python3 scripts/dbmigrate.py cd /app && export PYTHONPATH=/app/py && export PYSRV_CONFIG_PATH=/conf/server-conf.json && python3 scripts/dbmigrate.py

38
mikroman/testdb.py Normal file
View file

@ -0,0 +1,38 @@
import psycopg2
import time
import os
import json
# Step 1: Read connection details from server.json
def wait_for_postgres():
try:
with open('/conf/server-conf.json') as f:
config = json.load(f)
db_name = config['PYSRV_DATABASE_NAME']
db_user = config['PYSRV_DATABASE_USER']
db_password = config['PYSRV_DATABASE_PASSWORD']
db_host = config['PYSRV_DATABASE_HOST_POSTGRESQL']
db_port = config['PYSRV_DATABASE_PORT']
except Exception as e:
print(f"An error occurred: {e}")
exit(1)
print(f"Waiting for PostgreSQL database {db_name} to become available...")
while True:
try:
conn = psycopg2.connect(
dbname=db_name,
user=db_user,
password=db_password,
host=db_host,
port=db_port
)
conn.close()
print("PostgreSQL is ready!")
break
except psycopg2.OperationalError as e:
print(f"Database not ready yet. Retrying in 5 seconds...\nError: {e}")
time.sleep(5)
wait_for_postgres()