Deploying a Django application securely involves multiple components working together to ensure safety, scalability, and ease of maintenance. Using Docker, Nginx, and Let's Encrypt provides a robust solution for modern web deployment.

Prerequisites and Setup

Before starting, ensure you have the following installed on your server:

  • Docker and Docker Compose
  • Domain name pointing to your server IP
  • Basic knowledge of Django and Docker

Creating the Django Application

Start by creating a simple Django project. You can use the following commands:

django-admin startproject myproject

Configure your Django settings for production, including allowed hosts and static files handling.

Dockerizing the Django App

Create a Dockerfile in your project directory:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["gunicorn", "myproject.wsgi:application", "--bind", "0.0.0.0:8000"]

Also, create a docker-compose.yml file:

version: '3'

services:

web:

build: .

ports:

- "8000:8000"

Configuring Nginx as a Reverse Proxy

Create an Nginx configuration file, e.g., myproject.conf, with the following content:

server {

listen 80;

server_name yourdomain.com www.yourdomain.com;

location / {

proxy_pass http://127.0.0.1:8000;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

}

location /.well-known/acme-challenge/ {

root /var/www/html;

}

}

Securing with Let's Encrypt

Use Certbot to obtain SSL certificates:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

This command automatically configures Nginx to use SSL and redirects HTTP to HTTPS.

Final Deployment Steps

Start your Docker containers:

docker-compose up -d

Ensure your domain points to your server's IP address. Verify that your site loads securely with HTTPS.

Conclusion

Deploying Django with Docker, Nginx, and Let's Encrypt provides a secure and scalable environment. Automating SSL certificates and reverse proxy setup simplifies maintenance and enhances security for your web application.