docker compose for django

docker compose for django

Docker compose is used to deploy multiple services in the containers like Django application, PostgreSQL database and Running Django Migrations to create table in the database.

Dockerfile for Django application

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /app
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 8000
CMD [ "python", "manage.py", "runserver", "0.0.0.0:5000"]

Above Dockerfile starts with a Python 3image. It will create a directory and copies the django application and installs the required python packages and exposes the port 8000.

Docker compose file - "docker-compose.yml"

version: '3'
services:
  web:
    build: .
    container_name: djangoapp
    ports:
    - "8000:5000"
    volumes:
      - .:/app
      - logvolume01:/var/log
    links:
      - db
    depends_on:
      - db
  db:
    image: postgres
    container_name: djangoapp-db
    environment:
      POSTGRES_USER: test_user
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: test_db
    restart: unless-stopped
    ports:
      - "5435:5432"
    volumes:
      - data:/var/lib/postgresql/data

In above docker compose file under services we have three services.

  1. web - Django application
  2. db - Postgres database for django app

Let's build the images and start the services and create intial migrations using below commands

docker-compose build
docker-compose up -d
docker-compose run web python manage.py migrate

References:

  1. https://github.com/AnjaneyuluBatta505/docker-django-sample
  2. https://docs.docker.com/compose/django/