In this blog, I will show you how to init Django project from scratch Docker, with database is PostgreSQL and Redis for caching mechanism.
Prerequisites
- Must have Docker install in your machine
Step 1: Create a Django Project
mkdir django_project && cd django_project
python -m venv venv
source venv/bin/activate
pip install django
django-admin startproject myproject .// Start the development server
python manage.py runserver
Step 2: Create a Dockerfile
We will now containerize our Django application.
Inside django_project, create a Dockerfile:
# Use official Python image as base
FROM python:3.6.6
# Set the working directory in the container
WORKDIR /app
# Copy requirements file
COPY requirements.txt .
# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the Django project files
COPY . .
# Expose port 8000 for Django
EXPOSE 8000
# Run Django server
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "myproject.wsgi:application"]
Create requirements.txt
Django
gunicorn
psycopg2-binary
django-redis
Step 3: Set Up PostgreSQL and Redis with Docker Compose
We’ll use Docker Compose to define multiple services.
Create a docker-compose.yml file:
services:
  web:
    build: .
    container_name: django_app
    restart: always
    depends_on:
      - db
      - redis
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgres://myuser:mypassword@db:5432/mydatabase
    volumes:
      - .:/app
  db:
    image: postgres:14
    container_name: postgres_db
    restart: always
    environment:
      POSTGRES_DB: mydatabase
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
    ports:
      - "5432:5432"
    volumes:
      - pg_data:/var/lib/postgresql/data
  redis:
    image: redis:latest
    container_name: redis_cache
    restart: always
    ports:
      - "6379:6379"
volumes:
  pg_data:
Step 4: Configure Django to Use PostgreSQL and Redis
Update settings.py file:
import os
import dj_database_url
DATABASES = {
    'default': dj_database_url.config(default=os.getenv('DATABASE_URL'))
}
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://redis:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
Install dj-database-url:
pip install dj-database-url
echo "dj-database-url" >> requirements.txt
Step 5: Running the Application
Run the application with:
docker-compose up --build
Your Django app will be accessible at http://127.0.0.1:8000/.
To run it in the background:
docker-compose up -d
Step 6: Apply Migrations and Create a Superuser
Once the containers are running, run migrations inside the Django container:
docker exec -it django_app python manage.py migrate
docker exec -it django_app python manage.py createsuperuser
Step 7: Test Database and Caching
Create a model inside models.py:
from django.db import models
class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    def __str__(self):
        return self.namedocker exec -it django_app python manage.py makemigrations
docker exec -it django_app python manage.py migrate
Test Redis Caching
Modify views.py:
from django.core.cache import cache
from django.http import JsonResponse
from .models import Product
def get_products(request):
    products = cache.get('products')
    if not products:
        products = list(Product.objects.values())
        cache.set('products', products, timeout=60*5)  # Cache for 5 minutes
    return JsonResponse({'products': products})
Visit /get_products/ to see Redis caching in action.
Done!
