How do you perform Django database migrations when using Docker-Compose?

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

Leave a Comment