I have a fastapi application that connects to postgres. I've dockerized the application such that the api runs in one container and postgres runs in another container on the same network and they can talk to each other happily. I want to make some alembic migrations run every time I start the containers with docker compose up, and skip if neccessary tables and relations are already present.
I can start the api and have it talk to postgres without running the migrations (in which case requests sent to the api will cause errors due to the missing tables):
version: "3"
services:
api:
build: .
depends_on:
- postgres
ports:
- 8000:8000
volumes:
- ./:/usr/src/app
command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload #&& alembic upgrade head
environment:
- HOST=postgres
- DB
- DB_USER
- DB_PASSWORD
- JWT_SECRET
- JWT_ALGORITHM
- JWT_EXPIRY_MINUTES
- ALLOWED_ORIGINS
postgres:
image: postgres
environment:
- POSTGRES_PASSWORD
- POSTGRES_DB
volumes:
- postgres-db:/var/lib/postgresql/data
volumes:
postgres-db:
and I can run the migrations without starting the api:
version: "3"
services:
api:
build: .
depends_on:
- postgres
ports:
- 8000:8000
volumes:
- ./:/usr/src/app
command: alembic upgrade head #&& uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
environment:
- HOST=postgres
- DB
- DB_USER
- DB_PASSWORD
- JWT_SECRET
- JWT_ALGORITHM
- JWT_EXPIRY_MINUTES
- ALLOWED_ORIGINS
postgres:
image: postgres
environment:
- POSTGRES_PASSWORD
- POSTGRES_DB
volumes:
- postgres-db:/var/lib/postgresql/data
volumes:
postgres-db:
But if I use
alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
I get... sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "postgres" (172.25.0.2), port 5432 failed: Connection refused
and if I use
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload && alembic upgrade head
I get... sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users" does not exist 1-api-1 | LINE 1: INSERT INTO users (email, password) VALUES ('user1@me.com', ...
i.e. the migrations haven't run
What do I need to do to make postgres start up properly, THEN try to run the migrations, THEN start the api?