Docker for Django Developers: A Practical Guide
# Docker for Django Developers
Containerization has become essential for modern development. This guide will teach you how to Dockerize your Django applications.
## Why Use Docker?
- **Consistency**: Same environment everywhere (dev, staging, prod)
- **Isolation**: Dependencies don't conflict with your system
- **Portability**: Run anywhere Docker is installed
- **Scalability**: Easy horizontal scaling with orchestration
## Prerequisites
Install Docker Desktop for your operating system from [docker.com](https://docker.com).
## Project Structure
```
myproject/
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
├── .env
└── myproject/
├── manage.py
└── myproject/
└── settings.py
```
## The Dockerfile
```dockerfile
# Use official Python image
FROM python:3.11-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
gcc \
postgresql-client \
&& rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy project
COPY . .
# Collect static files
RUN python manage.py collectstatic --noinput
# Run the application
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "myproject.wsgi:application"]
```
## Docker Compose
For local development with PostgreSQL and Redis:
```yaml
version: '3.8'
services:
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
env_file:
- .env
depends_on:
- db
- redis
db:
image: postgres:15
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=myproject
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
redis:
image: redis:7-alpine
ports:
- "6379:6379"
celery:
build: .
command: celery -A myproject worker -l INFO
volumes:
- .:/app
env_file:
- .env
depends_on:
- db
- redis
volumes:
postgres_data:
```
## Environment Variables
Create a `.env` file:
```
DEBUG=1
SECRET_KEY=your-secret-key-here
DATABASE_URL=postgres://postgres:postgres@db:5432/myproject
REDIS_URL=redis://redis:6379/0
ALLOWED_HOSTS=localhost,127.0.0.1
```
## Django Settings
Update `settings.py` for Docker:
```python
import os
from pathlib import Path
import dj_database_url
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = os.environ.get('DEBUG', '0') == '1'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')
# Database
DATABASES = {
'default': dj_database_url.config(
default='sqlite:///db.sqlite3',
conn_max_age=600
)
}
# Redis Cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': os.environ.get('REDIS_URL', 'redis://localhost:6379/0'),
}
}
```
## Common Commands
```bash
# Build and start containers
docker-compose up --build
# Run in background
docker-compose up -d
# View logs
docker-compose logs -f web
# Run migrations
docker-compose exec web python manage.py migrate
# Create superuser
docker-compose exec web python manage.py createsuperuser
# Open Django shell
docker-compose exec web python manage.py shell
# Stop containers
docker-compose down
# Remove volumes (careful - deletes data!)
docker-compose down -v
```
## Production Considerations
### Multi-stage Builds
Reduce image size with multi-stage builds:
```dockerfile
# Build stage
FROM python:3.11-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
# Production stage
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /wheels /wheels
RUN pip install --no-cache /wheels/*
COPY . .
```
### Health Checks
```yaml
services:
web:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health/"]
interval: 30s
timeout: 10s
retries: 3
```
## Debugging Tips
1. **Container won't start?** Check logs: `docker-compose logs web`
2. **Can't connect to database?** Ensure `db` service is running and healthy
3. **Changes not reflecting?** Volumes might be cached, try `docker-compose down -v`
## Next Steps
- Set up CI/CD with GitHub Actions
- Deploy to AWS ECS or Google Cloud Run
- Implement Kubernetes for orchestration
Check out our Docker-ready Django templates in the marketplace!