Building DJANGO Application on Docker using Python

Building DJANGO Application on Docker using Python

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This remains me of EAR deployments in WebSphere in those years. Docker is a powerful tool for containerization, providing a consistent environment for applications to run across different systems. Combining Django with Docker simplifies the process of deploying and managing web applications.

In this article, we will walk through a sample DJANGO application within Docker container. We will cover creating few different types of URIs within DJANGO app, and then finally deploy in Docker.

Step 1: Setting & building Django application: below commands help in setting up django, start a project & create an application.

# Install Django using pip
py -m pip install django

# Create a new Django project named 'myproject'
py -m django-admin startproject myproject
cd myproject
py -m django startapp myapp        

Here is the sample Django code with three urlpatterns include Middleware class file. Sharing urls.py, views.py and middleware.py for reference.

#myapp/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('first/', views.first, name='first'),
    path('second/', views.second, name='second'), # New URL pattern for the second page
]

#myapp/views.py
from django.shortcuts import render
from django.contrib.staticfiles import finders

# Create your views here.
from django.http import HttpResponse

def index(request):
#   return HttpResponse("Welcome to my Django project!")
    return render(request, "index.html")

def first(request):
    return HttpResponse("Hi there First Page")

def second(request):
    return render(request, 'second.html')

#myproject/myproject/middleware.py (this the folder structure used to define class in this sample)
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

class MyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.META['PATH_INFO'] == '/game/':
            return HttpResponse('Tennis!')        

Step2 : Above django application can be deployed using python in the develpoment environment by using below command.

py manage.py runserver        

Step 3: For deploying in docker as a containerized application, we may need to first build an image using Dockerfile as shown below and then run as a docker container. The same docker build image can be customized for deployment on any orchestration like K8s, Google Run or ECR.

# pull official base image
FROM --platform=linux/amd64 python:3.9.0-slim-buster

RUN python3 -m venv venv

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip3 install --upgrade pip
RUN pip3 install Django --upgrade
RUN pip3 install gunicorn==20.1.0

# copy project
COPY . .

# Copy entrypoint script into the image
COPY entrypoint.sh /usr/src/app/entrypoint.sh

# Make entrypoint script executable
RUN chmod +x /usr/src/app/entrypoint.sh

# Define the entrypoint
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

#entrypoint.sh
#!/bin/bash
python manage.py migrate
# Start Gunicorn server
exec /usr/local/bin/gunicorn helloapp.wsgi:application --bind 0.0.0.0:8000

docker build -t django-image:latest .
docker run -p -d 8080:8000 --name django-container django-image:latest        

Notice that gunicorn library is deployed which is specific for linux environment helps in running Django container in the background.

Conclusion

We've demonstrated how to set up a Django application using Python and Docker containers. By containerizing our application, we ensure consistency across different environments and simplify the deployment process. With Docker , managing multi-container applications becomes straightforward, making it an excellent choice for deploying Django projects in production environments.


Abdelkhalek Bakkari

CEO and Founder of Smartovate | Ex-IBM?? Ex-Microsoft ????-| Top Project Management Voice on LinkedIn | Top Executive Management on LinkedIn

11 个月

This article offers a clear and practical guide for Docker and Django integration, complete with useful code examples. It's a great resource for those familiar with the basics, streamlining the containerization process. However, absolute beginners might struggle without additional context on Docker and Django fundamentals, and the Unix-specific deployment with Gunicorn may limit applicability for diverse development environments.

赞
回复

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

Srinivasan (Srini) Viswanathan的更多文章

  • ESO+AWS Secrets Manager

    ESO+AWS Secrets Manager

    What is External Secrets Operator? The External Secrets Operator is a tool designed to help manage secrets within…

  • Connection Between Doctor & Hotel Waiter

    Connection Between Doctor & Hotel Waiter

    Liveness & Readiness Probes In Kubernetes, both liveness and readiness probes help manage the health of your…

  • Automate Scaling with Terraform: Building an AWS Auto Scaling Group

    Automate Scaling with Terraform: Building an AWS Auto Scaling Group

    Scaling your EC2 instances based on demand is crucial for maintaining application performance and cost-efficiency. AWS…

  • Google native Logging & Observability

    Google native Logging & Observability

    In this article we will go through Google logging and monitoring tools hands-on to create a dashboard showing webserver…

    1 条评论
  • How to deploy a Java application as a Docker Container

    How to deploy a Java application as a Docker Container

    In this blog post, we will demonstrate the process of utilizing a HelloWorld.java sample application, constructing a…

  • Implementation of Containerization using Jenkins, GIT, Node.js & Docker

    Implementation of Containerization using Jenkins, GIT, Node.js & Docker

    Jenkins' Continuous Integration Pipeline serves as a powerful tool for automating diverse tasks pertaining to building,…

    2 条评论
  • Deploying WordPress on GKE Cluster with Persistent Disk and Cloud SQL

    Deploying WordPress on GKE Cluster with Persistent Disk and Cloud SQL

    In this tutorial, we will walk through the process of deploying a WordPress web application on Google Kubernetes Engine…

    1 条评论
  • Deploy multi-tier application in GKE using Terraform & Google SDK

    Deploy multi-tier application in GKE using Terraform & Google SDK

    wordpress+mysql deployment This article illustrates the process of deploying a WordPress application with a MySQL…

    1 条评论
  • Import Terraform Configuration

    Import Terraform Configuration

    google storage bucket & Virtual machine The command is used to bring existing infrastructure, which was not initially…

  • Store Terraform state in Cloud Storage

    Store Terraform state in Cloud Storage

    using S3 or Google Storage Bucket Terraform state file is a crucial component in Terraform's workflow. The content of…

社区洞察

其他会员也浏览了