|
| 1 | +#!/bin/bash |
| 2 | +set -e |
| 3 | + |
| 4 | +# Wait for database to be ready |
| 5 | +echo "Waiting for database..." |
| 6 | +python << END |
| 7 | +import sys |
| 8 | +import time |
| 9 | +import psycopg2 |
| 10 | +import os |
| 11 | +
|
| 12 | +# Get database connection details from environment variables |
| 13 | +host = os.environ.get("DB_HOST", "localhost") |
| 14 | +port = os.environ.get("DB_PORT", "5432") |
| 15 | +dbname = os.environ.get("DB_NAME", "postgres") |
| 16 | +user = os.environ.get("DB_USER", "postgres") |
| 17 | +password = os.environ.get("DB_PASSWORD", "postgres") |
| 18 | +
|
| 19 | +# Try to connect to the database |
| 20 | +start_time = time.time() |
| 21 | +timeout = 30 |
| 22 | +while True: |
| 23 | + try: |
| 24 | + conn = psycopg2.connect( |
| 25 | + host=host, |
| 26 | + port=port, |
| 27 | + dbname=dbname, |
| 28 | + user=user, |
| 29 | + password=password |
| 30 | + ) |
| 31 | + conn.close() |
| 32 | + print("Database is ready!") |
| 33 | + break |
| 34 | + except psycopg2.OperationalError as e: |
| 35 | + if time.time() - start_time > timeout: |
| 36 | + print(f"Could not connect to database after {timeout} seconds: {e}") |
| 37 | + sys.exit(1) |
| 38 | + print("Waiting for database to be ready...") |
| 39 | + time.sleep(2) |
| 40 | +END |
| 41 | + |
| 42 | +# Run makemigrations first to ensure migration files are created |
| 43 | +echo "Running makemigrations..." |
| 44 | +python manage.py makemigrations --noinput |
| 45 | + |
| 46 | +# Run migrations |
| 47 | +echo "Running migrations..." |
| 48 | +python manage.py migrate --noinput |
| 49 | + |
| 50 | +# Create superuser if needed |
| 51 | +if [ "$DJANGO_SUPERUSER_USERNAME" ] && [ "$DJANGO_SUPERUSER_PASSWORD" ] && [ "$DJANGO_SUPERUSER_EMAIL" ]; then |
| 52 | + echo "Creating superuser..." |
| 53 | + python manage.py createsuperuser --noinput |
| 54 | +fi |
| 55 | + |
| 56 | +# Collect static files |
| 57 | +if [ "$COLLECT_STATIC" = "true" ]; then |
| 58 | + echo "Collecting static files..." |
| 59 | + python manage.py collectstatic --noinput |
| 60 | +fi |
| 61 | + |
| 62 | +# Start server |
| 63 | +echo "Starting server..." |
| 64 | +exec "$@" |
0 commit comments