Setting up Django with Docker can streamline your development process, ensure consistency across environments, and simplify deployment. This tutorial provides a step-by-step guide for beginners to create a comprehensive Docker setup for Django projects.

Prerequisites

  • Basic knowledge of Django and Python
  • Installed Docker and Docker Compose on your machine
  • Text editor or IDE (e.g., VS Code)

Step 1: Create Your Django Project

Start by creating a new Django project if you haven't already. Open your terminal and run:

django-admin startproject myproject

Step 2: Set Up Docker Files

Dockerfile

Create a file named Dockerfile in your project directory with the following content:

FROM python:3.11-slim

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /app

COPY requirements.txt /app/
RUN pip install --upgrade pip && pip install -r requirements.txt

COPY . /app/

CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

docker-compose.yml

Create a docker-compose.yml file with the following configuration:

version: '3.8'

services:
  web:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - .:/app
    environment:
      - PYTHONDONTWRITEBYTECODE=1
      - PYTHONUNBUFFERED=1
    command: python manage.py runserver 0.0.0.0:8000
  db:
    image: postgres:13
    environment:
      POSTGRES_DB: mydatabase
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data/

volumes:
  postgres_data:

Step 3: Configure Django Settings

Update your settings.py to connect to the PostgreSQL database. Replace the default database configuration with:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': 'db',
        'PORT': '5432',
    }
}

Step 4: Install Dependencies

Create a requirements.txt file in your project directory and add:

Django>=4.0
psycopg2-binary

Step 5: Build and Run Containers

In your terminal, run the following commands:

docker-compose build
docker-compose up

Step 6: Finalize Django Setup

Once the containers are running, apply migrations and create a superuser:

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

Conclusion

With this setup, you now have a fully functional Django environment running inside Docker. This configuration simplifies development, testing, and deployment processes, making your workflow more efficient and consistent across different systems.