DEV Community

loading...
Cover image for 
Dockerzing a Python Django Web App on Ubuntu 21.04

Dockerzing a Python Django Web App on Ubuntu 21.04

Gautam Ankul
A Python developer to enhance our programming skill | Fractal.ai
・5 min read

Hey Developer!Today we're learn dockerize a django application on ubuntu It's worked all linux distro ...
This article covered a simple hello world django application In which we talk about Docker

prerequisite :

1.Ubuntu (any linux Distro)
2.Python Pip, the package manager
3.Python2 and Python3
4.Docker
5.Django

What is Docker
Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels.

What is Use of Docker
When building web applications, you have probably reached a point where you want to run your application in a fashion that is closer to your production environment. Docker allows you to set up your application runtime in such a way that it runs in exactly the same manner as it will in production, on the same operating system, with the same environment variables, and any other configuration and setup you require.

Means,Docker facilitate to Developer to work with from another existing project own system Docker container holds the entire package of application with own resources. like below example.

Alt Text

Now we are going for Docker installation in Ubuntu for that follow official link .Docker Installation Link

Check Docker version in your system like $ docker --version if it show like this Docker version 20.10.7, build f0df350
mean docker installed your system

Create Django Project in Pip Environment

Let us, make a directory and install pipenv in that directory

$ mkdir docker-project && cd docker-project

$ pipenv install django

Enter fullscreen mode Exit fullscreen mode

Now we Activate our Environment .

$ pipenv shell

Enter fullscreen mode Exit fullscreen mode

Now We are create a Django project and Django app..

$ django-admin startproject hello-project .

$ cd hello-project

$ python3 manage.py startapp pages

$ python3 manage.py migrate

Enter fullscreen mode Exit fullscreen mode

Now We are going to runserver for all set..

$ python3 manage.py runserver

Enter fullscreen mode Exit fullscreen mode

It's look like this.

Alt Text

At Now we are configure file and render hello world on web page let get start..

  1. Change in setting.py:
# hello_project/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages.apps.PagesConfig', # new

Enter fullscreen mode Exit fullscreen mode

2.Change in hello-project urls.py:

Now we can set the URL route for the pages app. Since we want our message to appear
on the homepage we’ll use the empty string '' . Don’t forget to add the include import
on the second line as well

# hello_project/urls.py

from django.contrib import admin
from django.urls import path, include # new
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')), # new
]
Enter fullscreen mode Exit fullscreen mode
  1. Change in pages view.py: Rather than set up a template at this point we can just hardcode a message in our view layer at pages/views.py which will output the string “Hello, World!”.
# pages/views.py

from django.http import HttpResponse
def home_page_view(request):
    return HttpResponse('Hello, World!')
Enter fullscreen mode Exit fullscreen mode

Note:We are create a file in pages (app directory) which name should be urls.py.

4.Change in page urls.py:
Within your text editor import path on the top line, add the home_page_view , and then
set its route to again be the empty string of '' . Note that we also provide an optional
name, home , for this route which is a best practice.

# pages/urls.py

from django.urls import path
from .views import home_page_view
urlpatterns = [
path('', home_page_view, name='home')
]

Enter fullscreen mode Exit fullscreen mode

Here we are done for configure and runserver and see like this page.

$ python3 manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Alt Text

Notice: Now are exit the Django virtual environment for docker configuration for quit pipenv.
(docker-project)$ exit
Enter fullscreen mode Exit fullscreen mode

Let’s create our first Dockerfile to see all of this theory in action.

$ touch Dockerfile

$ touch docker-compose.yml 
Enter fullscreen mode Exit fullscreen mode
Note: Here Dockerfile name should be D in Capital letter. And Project file structure must be like following image.

Alt Text

# Docerfile

#pull base image
FROM python:3.9
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
# Copy project
COPY . /code/

Enter fullscreen mode Exit fullscreen mode

Description:

Dockerfiles are read from top-to-bottom when an image is created. The first instruc-
tion must be the FROM command which lets us import a base image to use for our
image, in this case Python 3.9.
Then we use the ENV command to set two environment variables:
• PYTHONUNBUFFERED ensures our console output looks familiar and is not buffered
by Docker, which we don’t want
• PYTHONDONTWRITEBYTECODE means Python will not try to write .pyc files which we
also do not desire

Next we use WORKDIR to set a default work directory path within our image called code
which is where we will store our code.

For our dependencies we are using Pipenv so we copy over both the Pipfile and
Pipfile.lock files into a /code/ directory in Docker and so on.....

Note:
Our image instructions are now done so let’s build the image using the command
docker build . The period, . , indicates the current directory is where to execute the command.

Commad line

$ docker build .

...............................................
Sending build context to Docker daemon
154.1kB
Step 1/7 : FROM python:3.7
...
Step 7/7 : COPY . /code/
---> a48b2acb1fcc
Successfully built a48b2acb1fcc


Enter fullscreen mode Exit fullscreen mode

Moving on we now need to create a docker-compose.yml file to control how to run the
container that will be built based upon our Dockerfile image.

version: '3.7'

services: 
    web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8000
        volumes: 
            - .:/code
        ports: 
            - 8000:8000
Enter fullscreen mode Exit fullscreen mode

The final step is to run our Docker container using the command docker-compose up .
This command will result in another long stream of output code on the command line.

$ docker-compose up

........................................................
Creating network "hello_default" with the default driver
Building web
Step 1/7 : FROM python:3.7
...
Creating hello_web_1 ... done
Attaching to hello_web_1
web_1 | Performing system checks...
web_1 |
web_1 | System check identified no issues (0 silenced).
web_1 | September 20, 2019 - 17:21:57
web_1 | Django version 2.2.5, using settings 'hello_project.settings'
web_1 | Starting development server at http://0.0.0.0:8000/
web_1 | Quit the server with CONTROL-C.

Enter fullscreen mode Exit fullscreen mode

To confirm it actually worked, go back to http://127.0.0.1:8000/ in your web browser.
Refresh the page and the “Hello, World” page should still appear. because this application are running locally your's system.

Stop the container with Control+c (press the “Control” and “c” button at the same
time) and additionally type docker-compose down . Docker containers take up a lot of
memory so it’s a good idea to stop them in this way when you’re done using them.
Containers are meant to be stateless which is why we use volumes to copy our code
over locally where it can be saved.

$ docker-compose down

.............................
Removing hello_web_1 ... done
Removing network hello_default

Enter fullscreen mode Exit fullscreen mode

Great Developer's we are create Django application custom image and now we can upload this project image on Docker Hub

and fetch it and worked without any package installation error own your system locally.
Thank You!!

Discussion (3)

Collapse
amal profile image
Amal Shaji

You could use python:3.9.5-slim to build a smaller docker image.

Collapse
dhanushjatav profile image
Dhanush Jatav

please make some article about installation docker and it's all commands

Collapse
gautamankul profile image
Gautam Ankul Author

why not?