189

I have set up a Docker Django/PostgreSQL app closely following the Django Quick Start instructions on the Docker site.

The first time I run Django's manage.py migrate, using the command sudo docker-compose run web python manage.py migrate, it works as expected. The database is built inside the Docker PostgreSQL container just fine.

Changes made to the Django app itself are likewise reflected in the Docker Django container, the moment I save them. It's great!

But if I then change a model in Django, and try to update the Postgres database to match the model, no changes are detected so no migration happens no matter how many times I run makemigrations or migrate again.

Basically, every time I change the Django model, I have to delete the Docker containers (using sudo docker-compose rm) and start afresh with a new migration.

I'm still trying to get my head around Docker, and there's an awful lot I don't understand about how it works, but this one is driving me nuts. Why doesn't migrate see my changes? What am I doing wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
John
  • 5,581
  • 6
  • 29
  • 46
  • 1
    Did you figure out why? I get the answer below and it works: `You just have to log into your running docker container and run your commands.` but what is the reason that it behaves that way? @LouisBarranqueiro – lukik Sep 10 '17 at 10:30

9 Answers9

180

You just have to log into your running docker container and run your commands.

  1. Build your stack : docker-compose build -f path/to/docker-compose.yml
  2. Launch your stack : docker-compose up -f path/to/docker-compose.yml
  3. Display docker running containers : docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                         NAMES
3fcc49196a84        ex_nginx          "nginx -g 'daemon off"   3 days ago          Up 32 seconds       0.0.0.0:80->80/tcp, 443/tcp   ex_nginx_1
66175bfd6ae6        ex_webapp         "/docker-entrypoint.s"   3 days ago          Up 32 seconds       0.0.0.0:32768->8000/tcp       ex_webapp_1
# postgres docker container ...
  1. Get the CONTAINER ID of you django app and log into :
docker exec -t -i 66175bfd6ae6 bash
  1. Now you are logged into, then go to the right folder : cd path/to/django_app

  2. And now, each time you edit your models, run in your container : python manage.py makemigrations and python manage.py migrate

I also recommend you to use a docker-entrypoint for your django docker container file to run automatically :

  • collecstatic
  • migrate
  • runserver or start it with gunicorn or uWSGI

Here is an example (docker-entrypoint.sh) :

#!/bin/bash

# Collect static files
echo "Collect static files"
python manage.py collectstatic --noinput

# Apply database migrations
echo "Apply database migrations"
python manage.py migrate

# Start server
echo "Starting server"
python manage.py runserver 0.0.0.0:8000
Louis Barranqueiro
  • 10,058
  • 6
  • 42
  • 52
  • 37
    *I also recommend you to use a docker-entrypoint for your django docker container file to run automatically* - such operations should never be run automatically - I mean *migrate* especially. – Opal Nov 30 '15 at 10:02
  • 3
    why is that? we are in development environment. – Louis Barranqueiro Nov 30 '15 at 10:29
  • 14
    It doesn't matter on which environment you're - deployment should always look the same. If migrations are automated the might be run concurrently which is highly discouraged. E.g. on heroku - migrations are never run as a part of the deploy. – Opal Nov 30 '15 at 10:44
  • 6
    concurently? Here we are in a dev env. I run `makemigrations`. the next time that I launch my stack, `migrate` will update the database with the last migrations undone, otherwise django app will not works correctly... It just a shortcut in dev env to be sure you got the right database schema with the current app – Louis Barranqueiro Nov 30 '15 at 10:51
  • Thanks Louis. I've tried your steps #1 - #6, and still no joy. Makemigrations is still saying `No changes detected` , even though the app is crashing with missing table fields which means there are changes. Maybe I will start fresh in case my last experiments threw the migrations out of sync. Anyway, a quick question: shouldn't #2 have '-d' in it, so it's running in the background when I get to #4? I'm trying your entry point now, though I fear if makemigrations is seeing no changes, I wont get any migrations on startup anyway. Other than it not working for me yet, it's a very nice answer! – John Nov 30 '15 at 11:05
  • 3
    @LouisBarranqueiro, I meant multiple instances, single DB. – Opal Nov 30 '15 at 11:54
  • @Opal in this particular case, I agree with you. Typically, in staging or prod environment. That's why I talked about environment. – Louis Barranqueiro Nov 30 '15 at 12:22
  • @John about the `-d` flag, yes you can add it to use the same terminal window :D, otherwise, you just open an other window to run following commands. :) Could you add your `docker-compose.yml` file? Are you sure that your code is in a volume used by your django container? – Louis Barranqueiro Nov 30 '15 at 12:48
  • I tried your way again, with a freshly rebuilt container, and voila! It worked. Thanks a bunch. – John Dec 03 '15 at 04:08
  • couldn't you do this in a dockerfile called by compose... rather than using entrypoint.sh? – Kermit Jun 07 '19 at 20:16
  • 1
    For step 4, I would recommend: docker exec -ti $CONTAINER_ID /bin/sh – steamdragon Oct 09 '19 at 19:29
  • -f is not an option anymore with `docker compose build` https://docs.docker.com/compose/reference/build/ – Scott Skiles Oct 17 '19 at 14:59
  • to access the files i had to run "docker exec -t -i 66175bfd6ae6 sh" – tomstan11 Mar 01 '21 at 17:35
  • @LouisBarranqueiro Can you please elaborate on the usage of docker-entrypoint.sh? I don't get how is it automatic? I think it'll run every time we do **run** or **up**, but not every time I make any changes to my db model, because that's essentially when I'd like to make migrations / migrate. – Gopesh Khandelwal Mar 03 '23 at 14:51
85

I use this method:

services:
  web:
    build: .
    image: uzman
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "3000:3000"
      - "8000:8000"
    volumes:
      - .:/code
    depends_on:
      - migration
      - db
  migration:
    image: uzman
    command: python manage.py migrate --noinput
    volumes:
      - .:/code
    depends_on:
      - db

Using docker hierarchy we made, the service migration runs after setting up the database and before running the main service. Now when you run your service docker will run migrations before running the server; look that the migration server is applied over the same image as the web server, it means that all migrations will be taken from your project, avoiding problems.

You avoid making entry points or whatever other thing this way.

SalahAdDin
  • 2,023
  • 25
  • 51
  • 3
    How does `build: .` work with `image: ` I get the error that migration can't pull the named image – Aaron McMillin Feb 16 '18 at 16:21
  • 4
    I resolved it by putting the `build:` on `migration` since it will run before `web` – Aaron McMillin Feb 16 '18 at 16:23
  • 9
    Doesn't this keep the uzman image running and consuming RAM forever? Also, what *is* the uzman image? – mlissner Aug 10 '19 at 03:15
  • It is my custom docker image.I didn't test the RAM yet. – SalahAdDin Aug 10 '19 at 21:04
  • 1
    depends_on only guarantees that the migration service starts before the web service, but it does not ensure that the migration service has completed running migrations before the web service starts. In cases where the database takes longer to start or migrations take more time, this approach could still face issues. – aribo May 14 '23 at 22:00
57

Have your stack running then fire off a one shot docker-compose run command. E.g

#assume django in container named web
docker-compose run web python3 manage.py migrate

This works great for the built-in (default) SQLite database, but also for an external dockerized database that's listed as dependency. Here's an example docker-compose.yaml file

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

https://docs.docker.com/compose/reference/run/

Phalox
  • 38
  • 4
Oliver Shaw
  • 5,235
  • 4
  • 26
  • 35
31

You can use docker exec command

docker exec -it container_id python manage.py migrate
SuperNova
  • 25,512
  • 7
  • 93
  • 64
  • 2
    To get the container_id mentioned, do `docker ps` and then look for the column COMMAND for django server. – Jai Sharma Apr 30 '20 at 07:01
30

you can use docker-entrypoint.sh or a newer solution would be multiple comments in your docker-compose.yml

version: '3.7'

services:
  web:
    build: ./
    command: >
      sh -c "python manage.py collectstatic --noinput &&
             python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"
    volumes:
      - ./:/usr/src/app/
    ports:
      - 8000:8000
    env_file:
      - ./.env
    depends_on:
      - postgres

  postgres:
    image: postgres:13.0-alpine
    ports:
      - 5432:5432
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
Kelvin
  • 629
  • 7
  • 8
10

If you have something like this in your docker-compose.yml

version: "3.7"

services:

  app:
    build:
      context: .
      dockerfile: docker/app/Dockerfile
    ports:
    - 8000:8000
    volumes:
        - ./:/usr/src/app
    depends_on:
      - db

  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_USER: docker
      POSTGRES_PASSWORD: docker
      POSTGRES_DB: docker

Then you can simple run...

~$ docker-compose exec app python manage.py makemigrations
~$ docker-compose exec app python manage.py migrate
Robert Johnstone
  • 5,431
  • 12
  • 58
  • 88
  • 3
    Pretty sure makemigrations should be used during development time. By the time you push your build forward only migrate should be necessary. – Evandro Pomatti Jun 19 '22 at 00:20
  • Evandro's advice is right, AFAIK. However, I'm struggling to find a documentation link that says this explicitly. Can anyone share a link? – blong May 10 '23 at 16:18
6

Using docker exec, I was getting the following error:

AppRegistryNotReady("Models aren't loaded yet.")

So I used this command instead:

docker-compose -f local.yml run django python manage.py makemigrations
steamdragon
  • 1,052
  • 13
  • 15
4

I know this is old, and maybe I am missing something here (if so, please enlighten me!), but why not just add the commands to your start.sh script, run by Docker to fire up your instance? It will take only a few extra seconds.

N.B. I set the DJANGO_SETTINGS_MODULE variable to make sure the correct database is used, as I use different databases for development and production (although I know this is not 'best practice').

This solved it for me:

#!/bin/bash
# Migrate the database first
echo "Migrating the database before starting the server"
export DJANGO_SETTINGS_MODULE="edatool.settings.production"
python manage.py makemigrations
python manage.py migrate
# Start Gunicorn processes
echo "Starting Gunicorn."
exec gunicorn edatool.wsgi:application \
    --bind 0.0.0.0:8000 \
    --workers 3
timbit
  • 353
  • 2
  • 11
0

If you only want to use Dockerfile, you can add ENTRYPOINT[] command. Example how to run .sh script:

FROM python:3.9.4
RUN apt-get update
RUN apt-get install libpq-dev --assume-yes
RUN pip3 install psycopg2

COPY . /app
WORKDIR /app

RUN pip install -r requirements.txt
RUN pip3 install debugpy

ENTRYPOINT ["/app/docker-entrypoint.sh"]

CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
big-toni
  • 499
  • 4
  • 7
  • 2
    How does this solve the issue? – Ryan McGrath Sep 18 '21 at 03:10
  • 1
    on AWS i did not find a way to run docker-compose.yml in ECS task... so I optioned to use just Dockerfile , and run migrations from it (/app/docker-entrypoint.sh contains those commands) – big-toni Sep 18 '21 at 20:43