How to Dockerize Your Django Application

How to Dockerize Your Django Application

1. Install Docker Desktop:


2. Understand Containers & Images:

  • Images: Blueprints used to create containers, containing your app’s dependencies and configurations.
  • Example: A recipe or blueprint—like a cake recipe—you use to bake cakes.

  • Containers: Lightweight, portable environments that run your application.
  • Example: The actual cake made from the recipe, ready to eat or serve.


3. Prepare Your Django App for Docker:

  • Install gunicorn for production readiness:

pip install gunicorn
pip freeze > requirements.txt        

4. Create a Dockerfile:

The Dockerfile contains instructions to build your application image.

FROM python:3.8.3-slim

ENV PYTHONBUFFERED=1  # Useful for debugging

WORKDIR /dock_django

COPY requirements.txt .

RUN pip3 install -r requirements.txt

COPY . .

CMD python manage.py runserver 0.0.0.0:8000  # Make the app accessible outside the container        

Base Image: Choose a Python version from Docker Hub. Use slim variants (e.g., 3.8.3-slim) for smaller images.


5. Create a docker-compose.yaml File:

This file orchestrates multiple containers (if needed) and simplifies the build and run process.

version: "3.8"
services:
  app:
    build: .
    volumes:
      - .:/dock_django
    ports:
      - 8000:8000
    image: app:dock_django
    container_name: tanjiro_container
    command: python manage.py runserver 0.0.0.0:8000        

6. Build and Run the Container

Run the following commands:

  • Build the container:

docker-compose build        

  • Start the container:

docker-compose up        

  • Visit https://127.0.0.1:8000 to see your Django app live.

docker container


docker image

7. Environment Management

  • Use .env files to store sensitive data and configuration variables locally.
  • Example .env file:

SECRET_KEY=your_secret_key
POSTGRES_USER=your_db_username
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=your_db_name
POSTGRES_HOST=your_db_host        

  • Access these variables in Django:

#settings.py
import os

SECRET_KEY = os.environ.get('SECRET_KEY')
DB_USERNAME = os.environ.get('POSTGRES_USER')
DB_PASSWORD = os.environ.get('POSTGRES_PASSWORD')
DB_DATABASE = os.environ.get('POSTGRES_DB')
DB_HOST = os.environ.get('POSTGRES_HOST')
        

8. Clean Up Cache

Free up space by pruning unused Docker resources:

docker system prune        

Deploy Dockerized Django App on AWS with ECR and ECS

Step 1: Create and Push Docker Image to AWS ECR

1.Create an ECR Repository:

aws ecr create-repository --repository-name my-django-app        

2. Authenticate Docker with ECR:

aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <account_id>.dkr.ecr.<region>.amazonaws.com        

3. Build Docker Image:

docker build -t my-django-app .        

4. Tag the Docker Image:

docker tag my-django-app:latest <account_id>.dkr.ecr.<region>.amazonaws.com/my-django-app:latest
        

5. Push Image to ECR:

docker push <account_id>.dkr.ecr.<region>.amazonaws.com/my-django-app:latest        
repo
image

Step 2: Create a Task Definition for ECS

Create a JSON file (e.g., task-definition.json) with the following content:

{
  "containerDefinitions": [
    {
      "name": "my-django-application",
      "image": "<account_id>.dkr.ecr.<region>.amazonaws.com/my-django-app:latest",
      "memory": "256",
      "cpu": "256",
      "essential": true
    }
  ],
  "networkMode": "bridge",
  "family": "django-app-task-definition"
}
        

Step 3: Deploy to ECS

  1. Register Task Definition:

aws ecs register-task-definition --cli-input-json file://task-definition.json        

  1. Run the Task on ECS (EC2 or Fargate):

aws ecs create-service \
    --cluster <cluster-name> \
    --service-name my-django-app-service \
    --task-definition django-app-task-definition \
    --desired-count 1
        

Step 4: Configure ECS Cluster (EC2 Instance)

  1. Go to ECS Console > Clusters.
  2. Create a new cluster or use an existing one.
  3. Launch the EC2 instance or Fargate service to host the containers.

Your Django app should now be running on AWS ECS, powered by your Dockerized image from ECR!


10. Cluster Setup and Communication

  • Kubernetes Cluster: DigitalOcean provisions a cluster of virtual machines (Droplets) with Kubernetes installed. These act as worker nodes where your containers run.
  • VPC Network: Secure communication is established between your Kubernetes cluster and external services like databases (e.g., PostgreSQL).


11. Application Deployment

  • Deployments: Your deployment YAML describes how your app should run (replicas, image, ports, etc.). Kubernetes uses this to create and manage Pods (smallest deployable units containing your containers).

kubectl apply -f deployment.yaml  # Deploys the app
kubectl get deployments          # Verifies the deployment
kubectl get pods                 # Checks running pods
kubectl exec -t <podname> -- /bin/bash  # Access pod shell        

12. Networking and Exposing Services

  • Service Exposure: Kubernetes Services expose your app to the outside world:

kubectl get services
# OUTPUT:
# NAME               TYPE           CLUSTER-IP      EXTERNAL-IP      PORT(S)
# nginx-service      LoadBalancer   10.245.166.184  161.35.266.32    80:31988/TCP        

13. Scaling and Resource Management

  • Horizontal Scaling: Add more Pods to handle increased traffic.

kubectl scale deployment nginx-deployment --replicas=5
kubectl get pods  # Verify new pods        

  • Vertical Scaling: Adjust CPU/memory of existing Pods using resource limits in your YAML.
  • Rolling Updates: Update your app without downtime

kubectl set image deployment/nginx-deployment nginx=nginx:latest        

  • CI/CD Pipelines: Automate deployments with tools like GitHub Actions or Jenkins.


anime girl studying docker


Kunika Ingale

Junior Developer | Building Skills in Full-Stack Development & Problem-Solving | Young enthusiast | Lend A Hand India-Non-Profit Org

3 个月

This seems pretty interesting! I have some questions tho, can you please accept my request??

IQRA MANZOOR

Frontend Developer | IT Student | DSA | Leetcode | Writer | @icodeguru | Shaper at Global Shapers Community | Member at World Economic Forum

3 个月

You’re doing an amazing job! I’m truly inspired by how you excel and win every hackathon. I have a question—did you learn all your skills on campus, or did you develop them on your own?

Kunal Pandey

B.Tech CSE Student | Tech Enthusiast | Budding Software Developer | Passionate About AI, Machine Learning, and Innovative Problem-Solving

3 个月

This feels new and motivating... Dockerizing and deployment, will see more into it..

要查看或添加评论,请登录

ARYAN KYATHAM的更多文章

  • Tech toolkit for winning hackathons

    Tech toolkit for winning hackathons

    This toolkit consists of features/tech we integrated which helped me win 8+ hackathons.?? Ranging from AI, openCV…

    23 条评论
  • Deploying a Flask App to GCP using Docker and CI/CD

    Deploying a Flask App to GCP using Docker and CI/CD

    Step 1: Create requirements.txt First, list the dependencies for your Flask application in a file: Step 2: Create…

    15 条评论
  • AWS - Networking, Compute, Storage

    AWS - Networking, Compute, Storage

    Full article Here : Link, ? the repo :) Earlier, people used to set up rack servers manually on-premises, which was…

    3 条评论
  • Python fundamentals 1 shot

    Python fundamentals 1 shot

    Full Blog : Click Here ?? Python is a versatile programming language that supports both Object-Oriented Programming…

    7 条评论
  • How to win hackathons ?

    How to win hackathons ?

    Build awesome team Your vibe should match not only the skills. Don’t team up with people with whom you ain’t…

    10 条评论
  • AI Powered Developer Guru

    AI Powered Developer Guru

    In software development, a significant portion of a developer's time—up to 60%—is spent not in writing code, but in…

  • Deploying Django on AWS Elastic Beanstalk

    Deploying Django on AWS Elastic Beanstalk

    Introduction: In this tutorial, we will walk through the process of deploying a Django application on AWS Elastic…

    2 条评论
  • Deploy dJango app on AWS using EC2, RDS, S3 !

    Deploy dJango app on AWS using EC2, RDS, S3 !

    ?? Launch Django Project on AWS with EC2, S3, RDS, Nginx, Gunicorn! ?? What is EC2 Instance ? : EC2 allows us to…

    1 条评论
  • Revolutionizing Billboard Analytics with Artificial Intelligence & Data Science.

    Revolutionizing Billboard Analytics with Artificial Intelligence & Data Science.

    What is Billboard Analytics ? Billboard analytics is the process of analyzing data related to outdoor advertising, such…

    3 条评论