Docker Community Forums

Share and learn in the Docker community.

Docker Compose With Django Rest and Postgres


I am trying to build a compose file for an a Django API which uses postgres as a database.
I am struggling to work out how to actually make it work.
My main issue is I need to do these things (in this order) and i am not seeing any guides which exactly match this.
1-Start up the postgres
2-run the commands (only after postgres is ready)

python3 /projectB/ makemigrations &&
python3 /projectB/ migrate

3-Insert Data for a default user so I can login (to the application itself) but this needs to happen after the migrations because they are what create the tables
4-run the server using:

python3 projectB/ runserver

So far on my own I can get 1,2 and 4 working but despite best efforts I can’t seem to make it cooperate with any psql
This is my compose file

version: '3'
image: postgres
  context: .
  dockerfile: docker/db-init/Docker
  - db
build: .
command: > 
    bash -c " /python3 projectB/ makemigrations &&
    python3 /projectB/ migrate &&
    python3 /projectB/ runserver"
  - .:/projectB/
  - "8000:8000"
  - db-init

The stuff under db-init just forces the django to wait for postgres to properly start.
it does have a dockerfile like this:

RUN apt-get update && \
    apt-get install -y postgresql-client && \
    rm -rf /var/lib/apt/lists/*
CMD [ "./docker/db-init/", "db", "./docker/db-init/" ] contains the psql (and duplicate migrations stuff because ideally it would be here instead but it never runs from here)


python3 ./projectB makemigrations
python3 ./projectB migrate --no-input
psql -U postgres -d "postgres" -c "INSERT INTO "user" VALUES (NULL, 'admin', 'Password', 'Default', 'Admin', '', NULL, True, 0);"

Any time I try to add a volume for the postgres it breaks everything (Nothing can find the db anymore)
Any time i put psql commands in a bash script it does nothing (Only bash that works is waiting for postgres)
I even tried just putting the psql commands into the command part of the compose file but it doesnt know what psql means.

What is the correct way that I should be going about this?