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
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.
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.
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
).
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.