CODE WITH SIBIN

Solving Real Problems with Real Code


Deploying a Django application on AWS App Runner

AWS App Runner is a fully managed service that makes it easy to deploy containerized web applications and APIs. This guide provides a deep, comprehensive walkthrough of deploying a Django application on AWS App Runner, covering setup, configuration, best practices, and advanced optimizations.

Table of Contents

  1. Introduction to AWS App Runner
  2. Why Use App Runner for Django?
  3. Prerequisites
  4. Step-by-Step Deployment
  5. Configuring Django for Production
  6. Database Setup (RDS, DynamoDB)
  7. Static & Media Files (S3, CloudFront)
  8. Domain & HTTPS (Route 53, ACM)
  9. CI/CD Pipeline (CodePipeline, GitHub Actions)
  10. Monitoring & Logging (CloudWatch, X-Ray)
  11. Scaling & Performance Optimization
  12. Security Best Practices
  13. Cost Optimization
  14. Troubleshooting Common Issues
  15. Alternatives to App Runner (Elastic Beanstalk, ECS, Lightsail)

1. Introduction to AWS App Runner

AWS App Runner is a fully managed service that:

  • Automatically builds & deploys from source code or container images.
  • Handles load balancing, scaling, and security patches.
  • Supports custom domains, HTTPS, and VPC integration.
  • Works seamlessly with Docker containers.

Key Features:
✅ Automatic Scaling (Handles traffic spikes)
✅ Managed HTTPS (Free SSL via ACM)
✅ VPC Support (Secure database access)
✅ CI/CD Integration (GitHub, ECR, CodePipeline)

2. Why Use App Runner for Django?

  • No Server Management: Unlike EC2, no need to manage servers.
  • Fast Deployments: Deploy in minutes with minimal config.
  • Cost-Effective: Pay per request (good for low-mid traffic).
  • Scalable: Auto-scales based on demand.

When to Avoid App Runner?

  • Need GPU support (use ECS/EKS instead).
  • Require persistent storage (use EFS with ECS).
  • Need granular control over infrastructure.

3. Prerequisites

Before deploying:

  • AWS Account (Free Tier eligible)
  • Django Project (Ready for production)
  • Docker Installed (For containerization)
  • AWS CLI Configured (aws configure)
  • PostgreSQL / MySQL (For production DB)

4. Step-by-Step Deployment

4.1. Containerizing Django with Docker

Create a Dockerfile:

# Use official Python image
FROM python:3.9-slim

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# Set work directory
WORKDIR /app

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy project
COPY . .

# Collect static files (if needed)
RUN python manage.py collectstatic --noinput

# Run Gunicorn (production WSGI server)
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "your_project.wsgi:application"]

Create a .dockerignore:

.env
*.sqlite3
*.pyc
__pycache__

4.2. Pushing to Amazon ECR

  • Create an ECR Repository:
aws ecr create-repository --repository-name django-app
  • Authenticate Docker:
aws ecr get-login-password | docker login --username AWS --password-stdin YOUR_ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com
  • Build & Push:
docker build -t django-app .
docker tag django-app:latest YOUR_ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/django-app:latest
docker push YOUR_ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/django-app:latest

4.3. Creating an App Runner Service

  1. Go to AWS App Runner → Create Service.
  2. Select Container registry → Amazon ECR.
  3. Choose your ECR repository and image.
  4. Configure:
    • Service namedjango-app
    • Port8000
    • Auto-deploy: Enable (for CI/CD)
  5. Set Environment Variables (e.g., SECRET_KEYDATABASE_URL).
  6. Click Create & Deploy.

5. Configuring Django for Production

Update settings.py:

DEBUG = False
ALLOWED_HOSTS = ["your-app.run.apprunner.amazonaws.com", "yourdomain.com"]

# Database (PostgreSQL recommended)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST'),
        'PORT': os.getenv('DB_PORT', '5432'),
    }
}

# HTTPS Settings
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

6. Database Setup (RDS, DynamoDB)

  • Amazon RDS (PostgreSQL/MySQL):
    • Create a PostgreSQL RDS instance in the same VPC.
    • Configure security groups to allow App Runner access.
  • DynamoDB (For NoSQL):
    • Use django-dynamodb for session storage.

7. Static & Media Files (S3, CloudFront)

  • Create an S3 Bucket:
aws s3 mb s3://your-django-static-bucket
  • Install django-storages:
pip install django-storages[boto3]
  • Configure settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = 'static/'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'
AWS_STORAGE_BUCKET_NAME = 'your-django-static-bucket'
AWS_S3_REGION_NAME = 'us-east-1'

8. Domain & HTTPS (Route 53, ACM)

  1. Buy a domain in Route 53.
  2. Request an ACM Certificate.
  3. Add a Custom Domain in App Runner.
  4. Update ALLOWED_HOSTS.

9. CI/CD Pipeline

Option 1: AWS CodePipeline

  • Connect to GitHub → Build → Deploy.

Option 2: GitHub Actions

name: Deploy Django to App Runner
on:
  push:
    branches: [ main ]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: docker build -t django-app .
      - run: aws ecr get-login-password | docker login --username AWS --password-stdin $ECR_REGISTRY
      - run: docker push $ECR_REGISTRY/django-app:latest

10. Monitoring & Logging

  • CloudWatch Logs: View App Runner logs.
  • AWS X-Ray: Trace requests for performance insights.
  • Health Checks: Configure in App Runner.

11. Scaling & Performance Optimization

  • Auto Scaling: Adjust CPU/Memory in App Runner.
  • Caching: Use ElastiCache (Redis).
  • CDN: CloudFront for global static files.

12. Security Best Practices

  • IAM Roles: Least privilege for App Runner.
  • Secrets Management: Use AWS Secrets Manager.
  • VPC Isolation: Keep DB in private subnet.

13. Cost Optimization

  • Use Free Tier (750 hrs/month free).
  • Scale-to-Zero: If low traffic, consider Lambda.

14. Troubleshooting Common Issues

  • 502 Bad Gateway: Check Gunicorn logs.
  • Database Connection Errors: Verify VPC settings.
  • Static Files Not Loading: Check S3 permissions.

15. Alternatives to App Runner

ServiceBest ForComplexity
Elastic BeanstalkFull Django stack (EC2-based)Medium
ECS FargateAdvanced container orchestrationHigh
LightsailSimple deploymentsLow

Final Thoughts

AWS App Runner is an excellent choice for Django deployments when you want:
✔ Fast setup
✔ Managed infrastructure
✔ Auto-scaling

For highly complex apps, consider ECS/EKS.

Leave a Reply

Your email address will not be published. Required fields are marked *