Prompt
postgresql startup app database
Latest observation
If you want a PostgreSQL database to exist at app startup, the usual approach is:
- Start PostgreSQL service/container
- Create the database if it doesn’t exist
- Run schema migrations / table creation
- Start the app
Common ways to do it
1) Application startup script
Use a startup script that checks for the DB and creates it if missing.
Example shell script:
#!/bin/sh
set -e
until pg_isready -h localhost -p 5432; do
echo "Waiting for PostgreSQL..."
sleep 2
done
createdb -h localhost -U postgres myappdb 2>/dev/null || true
python app.py
2) Docker Compose
If you’re using Docker, define both app and postgres services.
services:
db:
image: postgres:16
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: secret
POSTGRES_DB: myappdb
ports:
- "5432:5432"
app:
build: .
depends_on:
- db
environment:
DATABASE_URL: postgres://postgres:secret@db:5432/myappdb
Note: depends_on does not wait for Postgres to be ready, only started. You still need a readiness check.
3) Init script for PostgreSQL container
If you want PostgreSQL itself to create setup objects on first startup, mount SQL files into:
/docker-entrypoint-initdb.d/
Example:
CREATE DATABASE myappdb;
This runs only when the database cluster is first initialized.
4) Migration tool
For real applications, use migrations:
- Flyway
- Liquibase
- Alembic (Python)
- Prisma Migrate
- Rails migrations
This is the best practice instead of manually creating tables in startup code.
Important note
If you mean “create the PostgreSQL database when the app starts,” PostgreSQL does not automatically create arbitrary databases for your app unless:
- you use
POSTGRES_DBin the container, or - your startup code runs
CREATE DATABASE, or - you place init SQL in
/docker-entrypoint-initdb.d/
If you want, I can give you a ready-to-use example for:
- Node.js
- Python
- Java/Spring Boot
- Docker Compose