Docker + Django + Redis + Celery Complete Setup Guide
Docker + Django + Redis + Celery Complete Setup Guide
This is a real production-level architecture.
Architecture
-
Django → Web App
-
PostgreSQL → Database
-
Redis → Broker
-
Celery → Background tasks
-
Nginx → Reverse proxy
Key Technologies
-
Django
-
Redis
-
Celery
-
PostgreSQL
Django Celery Config
# project/celery.pyfrom celery import Celeryimport osos.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")app = Celery("project")app.config_from_object("django.conf:settings", namespace="CELERY")app.autodiscover_tasks()settings.py
CELERY_BROKER_URL = "redis://redis:6379/0"Now you can run:
docker-compose up --buildDocker Production Deployment on AWSWhen deploying to cloud, common options:
Amazon ECS
Amazon EKS
AWS Elastic Beanstalk
Amazon EC2
Simple Production Setup (EC2 + Docker)
Step 1: Launch EC2
Ubuntu instance
Open ports 80 & 443
Step 2: Install Docker
sudo apt updatesudo apt install docker.ioStep 3: Pull Image
docker pull yourdockerhub/django-appStep 4: Run with Nginx Reverse Proxy
Use:
Gunicorn inside container
Nginx on host or container
HTTPS via Certbot
Production Best Practices
Use environment variables
Use secrets manager
Enable logging
Use health checks
Auto-scaling group
Use RDS instead of container DB
Dockerfile Optimization Deep Dive
Bad Dockerfile
FROM python:3.12COPY . .RUN pip install -r requirements.txtCMD ["python", "app.py"]Problems:
Large image
No caching
Copies everything
Optimized Version
FROM python:3.12-slimENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1WORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .USER nobodyCMD ["gunicorn", "project.wsgi:application", "--bind", "0.0.0.0:8000"]Multi-Stage Example
FROM python:3.12 as builderWORKDIR /installCOPY requirements.txt .RUN pip install --prefix=/install -r requirements.txtFROM python:3.12-slimWORKDIR /appCOPY --from=builder /install /usr/localCOPY . .CMD ["python", "app.py"]Key Optimization Tips
Order layers properly
Use slim images
Use specific versions
Clean apt cache
Reduce build context
Avoid root user
Use healthcheck
Example:
HEALTHCHECK CMD curl --fail http://localhost:8000 || exit 1
Comments
Post a Comment