Dockerizing Django Application: How to Containerize Python Web App

Dockerizing Django Application: How to Containerize Python Web App. In this post, we introduce Django, importance of Dockerizing Django application then show you how to containerize a Python web application.

Django web framework is a good choice if you’re developing a web application that uses cross site scripting and supports a huge user base. Its vast community support enables users or programmers to easily connect and get assistance if necessary.

Shall we start with Dockerizing Django Application: How to Containerize Python Web App.

What is Django?

Primarily, Django is a free, Python framework used by most developers for building complex database driven websites. The open source framework is quick and speeds up your entire development process of a web application. 

Anyone with a basic understanding of programming may create a web application thanks to Django’s stack development approach. It is appropriate for larger projects due to its many benefits over more conventional methodologies, including scalability and flexibility. In fact, developers may quickly create a feature-rich, secure, and scalable web frontend with the help of the Django web framework when installed on a web server.

It even comes with API connectivity and user authentication features. Also, it allows you to customize your features without having to completely rewrite the code. Moreover, it even has integrated security features that defend against malicious assaults. Further, the ORM (Object Relational Mapper) makes data administration operations like accessing databases and building models simpler.

Another advantage of choosing Django over other frameworks it may be used for various project types and even Django REST APIs. Highly extensible and includes a powerful set of application programming interfaces (APIs). What is more, Django has a robust administration interface that facilitates website management and permits content customization, including static files and media.

Benefits of Dockerizing Your Django Application

The Dockerizing process includes packaging, deployment, and running applications with the help of Docker containers. Well, Docker is a free software programme that ships your application with all required features included. If you want to distribute your application as a single package called a container, you may use Docker to bundle it with everything it needs to run (such as libraries).

It works similarly to a virtual environment but differs in a certain way. Simply, Docker offers a degree of isolation above the operating system (OS), whereas virtual environments offer a layer of isolation within the OS. Docker offers a number of advantages for your Django project by running distinct containers on top of the OS, such as:

1. Manage Dependencies – Using a Dockerfile, which contains a list of all the necessary packages and libraries, Docker enables you to specify the dependencies of your application. This makes maintaining dependencies easier and guarantees that everyone on the team is using the same set of dependencies, reducing any compatibility issues.

2. Easy to Setup – With the use of Docker, put your Django application’s configuration and dependencies inside of a container easily without any hassle. This makes it simple to configure and even locally replicate the same environment across other machines. It adds more consistency and lowers the possibility of compatibility issues.

3. Highly Portable – Docker containers help package your application and dependencies into a single container, which creates isolation from the host system. This isolation guarantees that your programme functions consistently regardless of the host environment beneath it, making it highly portable and lowering the possibility of clashes with other apps or system configurations.

4. Simple Deployment – Another benefit it dockerizing your Django application is it helps streamline the deployment process. Developers no longer need to install dependencies manually or perform host system configuration in order to deploy this container to various environments, such as development, staging, or production.

5. Continuous Integration and Deployment – Docker interacts effectively with CI/CD pipelines which are used to build software. A streamlined and effective development workflow is ensured by containerizing your Django application so that you easily create, test, as well as deploy applications using automated CI/CD technologies.

Dockerizing Django Application: How to Containerize Python Web App

In this section, we show you how to create a Django application and Dockerize it with Docker.

Prerequisites

  • A root user or a user with sudo privileges.

Getting Started

Before starting, it is always a good idea to update all your system packages to the latest version. Run the following commands to update and upgrade all the packages.

				
					apt update -y
apt upgrade -y
				
			

After completing system updates, install other required packages using the following command.

				
					apt install apt-transport-https ca-certificates curl software-properties-common
				
			

Once all the packages are installed, please proceed to install Docker.

Install Docker Engine

Now, you need a Docker engine to containerize any application. Ubuntu’s default repository does not contain the latest Docker version. So you need to add Docker’s official repository to get the latest Docker version.

First, add the Docker GPG key using the following command.

				
					curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
				
			

Next, add Docker official repository using the following command.

				
					add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"
				
			

Finally, update the repository cache and install Docker using the command given below.

				
					apt install docker-ce -y
				
			

After the successful installation, verify the Docker installation using the following command.

				
					docker version
				
			

You see the Docker information on the following screen.

Install Python

Django is a Python based application. So you also need to install Python and other dependencies to your server. Run the following command to install all of them.

				
					apt install python3 python3-pip
				
			

After the Python installation, you verify the Python version with the following command.

				
					python3 --version
				
			

You should see the Python version in the following output.

				
					Python 3.10.6
				
			

Create a Django Project

First, create a Django project directory.

				
					mkdir django
				
			

Next, navigate to the django directory and install the Django package using the pip command.

				
					cd django
pip3 install Django
				
			

Next, create a new Django project using the django-admin tool.

				
					django-admin startproject djangoproject
cd djangoproject
				
			

Then, run the django project using the following command.

				
					python3 manage.py runserver
				
			

If everything is fine, you see the following output.

				
					July 08, 2023 - 10:54:12
Django version 4.2.3, using settings 'djangoproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

				
			

Press the CTRL+C to stop the server.

Setting Up a Django Application

In this section, we install Django and create a minimal Django application. We then Dockerize this application in the later section.

Let’s create a new application called djangoapp using the following command.

				
					python3 manage.py startapp djangoapp
				
			

Next, edit the settings.py file and define your server ip and add your application name.

				
					nano djangoproject/settings.py
				
			

Modify the following lines.

				
					ALLOWED_HOSTS = ['209.23.10.215']

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djangoapp', # <-- ADD THIS LINE
]

				
			

Next, edit the views.py file.

				
					nano djangoapp/views.py
				
			

Define a djangoapp function to render the djangoapp.html file.

				
					from django.shortcuts import render

def djangoapp(request):
return render(request, 'djangoapp.html', {})

				
			

Next, create a templates directory and create a djangoapp.html file inside it.

				
					mkdir djangoapp/templates/
nano djangoapp/templates/djangoapp.html
				
			

Add the following code.

				
					<h1>Hello, World!</h1>
				
			

Next, edit the urls.py file to access your created HTML page.

				
					nano djangoproject/urls.py
				
			

Modify the following lines.

				
					from django.contrib import admin
from django.urls import path, include # <-- ADD THIS LINE

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('djangoapp.urls')), # <-- ADD THIS LINE
]

				
			

Next, create a djangoapp.urls module for your application.

				
					nano djangoapp/urls.py
				
			

Add the following lines.

				
					from django.urls import path
from djangoapp import views

urlpatterns = [
path('', views.djangoapp, name='djangoapp'),
]
				
			

Finally, migrate all the changes using the following command.

				
					python3 manage.py migrate
				
			

You should see the following screen.

Now, run your application using the following command.

				
					python3 manage.py runserver
				
			

Now access your Django application using the URL http://your-server-ip:8000. This shows you your application on the following screen.

Dockerize Django Application

In this section, we create a Dockerfile inside the Django project and shows you how to build the Docker image for your Django application and run it inside the container.

First, navigate to your main Django directory and create a Dockerfile.

				
					cd ..
nano Dockerfile
				
			

Add the following lines.

				
					FROM python:3.10.6

RUN pip3 install Django

# Mounts the application code to the image
COPY . code
WORKDIR /code

EXPOSE 8000

# runs the production server
ENTRYPOINT ["python3", "djangoproject/manage.py"]
CMD ["runserver", "0.0.0.0:8000"]

				
			

The above code pulls Python image from the DockerHub registry, copy all your application files inside the container and run your application on port 8000.

Now, build your application image using the Dockerfile as shown below.

				
					docker build -t python-django-app .
				
			

You should see the following screen.

To verify your created image, run the following command.

				
					docker images
				
			

You see your Django image in the following output.

				
					REPOSITORY TAG IMAGE ID CREATED SIZE
python-django-app latest f2591c9535fc About a minute ago 963MB
				
			

Run the Django Container

At this point, the Docker image for the Django application is ready. Now run the following command to create a container to run your application.

				
					docker run -dit -p 8000:8000 --name python-django-container python-django-app
				
			

If everything is fine, you see the following output.

				
					b9884c202d30db6013f8c3785364971dcf751c6f14d1e9cc4177306ea7513857
				
			

Now verify your running container using the following command.

				
					docker ps
				
			

This shows you the running container and port on the following screen.

To check the Django container log, run the following command.

				
					docker logs python-django-container
				
			

You should see your application logs in the following screen.

check docker logs

Now, open your web browser and access your containerize Django application using the URL http://your-server-ip:8000. You should see your rendered HTML page on the following screen.

Dockerizing Django Application: How to Containerize Python Web App Conclusion

In this step by step guide, we have created a Django project, create a simple application, and test it on the server. Then, we explained to create a Dockerfile for the Django application, build the Docker image, and run the Django application inside the Docker container. I hope you now easily Dockerize your application and use it in the production environment.

By dockerizing your Django applications, you improve your deployment process as well as streamline all your deployment workflows. Further, it gives your Django application a consistent environment throughout all of its lifecycle stages.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x