Why am I unable to run django migrations via the 'docker-compose run web' command?

后端 未结 2 1073
情话喂你
情话喂你 2021-02-01 23:05

So I am deploying django, postgress and nginx containers via docker-compose and I have an issue that I can\'t seem to figure out.

In order to resolve the following error

相关标签:
2条回答
  • 2021-02-01 23:45

    docker-compose run creates new containers

    You have already noticed the problem. When you use docker-compose run, a new container is created.

    When you ran the first command (makemigrations), a new container was created, makemigrations ran, and the migration files were written to the (new) container's filesystem.

    When you ran the second command (migrate), another new container was created. The migration ran, but it had nothing to do. That's because the migration files were not available - they were written in a different container than this new one.

    You can solve this in a couple of ways.

    Using docker-compose exec

    First, you can do what you already did, but use docker-compose exec instead of run.

    docker-compose exec web python manage.py makemigrations 
    docker-compose exec web python manage.py migrate
    

    exec will use the already-running container, rather than creating new containers.

    Using an entrypoint script

    Another option is to use an entrypoint script and run the migration there, before the server is started. This is the way to go if you'd prefer things to be more automatic.

    Dockerfile:

    COPY entrypoint.sh /entrypoint.sh
    RUN chmod +x /entrypoint.sh
    

    entrypoint.sh:

    #!/bin/sh
    python manage.py makemigrations
    python manage.py migrate
    exec "$@"
    

    docker-compose.yml (under 'web'):

    entrypoint: /entrypoint.sh
    

    In this scenario, when the container starts, the entrypoint script will run, handle your migration, then hand off to the command (which in this case is Django runserver).

    The new containers loop forever

    As you noticed, the new containers stay running. That is normally unexpected, because you overrode the command with one that should exit (rather than stay running). However, in docker-compose.yml, you specified restart: always. So they will run the migration commands over and over, restarting each time the command exits.

    0 讨论(0)
  • 2021-02-01 23:47

    Dan Lowe gave a very nice answer, but the entrypoint script was not working for me. The problem is that some "makemigrations" expect your input, for instance "yes"/"no".

    You can complement Dan Lowe answer with:

    python manage.py makemigrations --noinput
    

    instead of

    python manage.py makemigrations
    

    (This works at least for simple "yes"/"no" questions)

    0 讨论(0)
提交回复
热议问题