How to perform Python django database migrations when using docker-compose?

Estimated read time 2 min read

Performing database migrations in a Dockerized Django application using Docker Compose involves the following steps:

  1. Create a Dockerfile for the Django application and include the required dependencies and configurations.
  2. Create a docker-compose.yml file that defines the services required for the application, including the database service.
  3. Build and run the containers using docker-compose up.
  4. Open a shell in the Django container using docker exec -it <container_id> bash.
  5. Run the python manage.py makemigrations command to create new migrations based on the changes made to your models.
  6. Run the python manage.py migrate command to apply the migrations to the database.

Here’s an example docker-compose.yml file:

version: "3"

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: <db_user>
      POSTGRES_PASSWORD: <db_password>
      POSTGRES_DB: <db_name>
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

In the web service, we define the build context for our Django application and map the container’s port to the host machine’s port.

After running docker-compose up, open a new terminal and navigate to the directory containing the docker-compose.yml file. Then, execute the following command to open a shell in the Django container:

docker exec -it <container_id> bash

Finally, execute the following commands to perform the database migrations:

python manage.py makemigrations
python manage.py migrate

Note that <container_id> in the docker exec command should be replaced with the actual ID of the container running the Django application.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply