Guide
April 1th

Docker python django tutorial. Dockerize a Python django App in 3 minutes.

This is a brief tutorial that presents how you can run a simple 'Hello World'-style web application written in Django in docker.

Requeriments

You should have python3 installed. To check which version of python do you have installed, just run:

python --version

Step 1 - Set Up Your Development Environment

Whenever you are starting a new web development project, it’s a good idea to first set up your development environment. So, let's create a new directory for your project to live in, and move into it:

$ mkdir tutotial
$ cd tutorial

Once your inside the main directory, it’s a good idea to create a virtual environment to manage dependencies. There are many different ways to set up virtual environments, but here you’re going to use venv:

$ python3 -m venv <name>

This command will create a folder venv in your working directory. Inside this directory, you’ll find several files including a copy of the Python standard library. Later, when you install new dependencies, they will also be stored in this directory. Next, you need to activate the virtual environment by running the following command:

$ source <name>/bin/activate

You’ll know that your virtual environment has been activated, because your console prompt in the terminal will change. Itß should look something like this:

(<name>) $

header image

Step 2 - Create a Django Project

Once you have a python virtual environment enable, you need to add the standard Python project dependencies file which is usually named requirements.txt, and the Django dependency to it. Good, once you have created and added the dependencies, the file should look like this:

$ cat requirements.txt
Django==2.2.5

With the Django dependency added, you can then install Django using the following command:

$ pip install -r requirements.txt

Once installed, you will find that you now have access to the django-admin command line tool, which you can use to generate the project files and directory structure needed for the simple “Hello, World!” application.

$ django-admin startproject mysite

Let’s take a look at the project structure the tool has just created for you:

.
├── mysite
│   ├── mysite
│   │   ├── __init__.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
└── requirements.txt

You can control the application for development purposes using the manage.py file, which allows you to start the development test web server for example:

$ cd mysite
$ python manage.py runserver

header image

Then, in your browser go to http://127.0.0.1:8000/, and you should see the following:

header image

Congratulations, you’ve created a Django site! The next step is to create apps so that you can add views and functionality to your site.

Step 3 - Create a Django Application

To create the app, run the following command:

$ python manage.py startapp hello_world

This will create another directory called hello_world with several files:

  • __init__.py tells Python to treat the directory as a Python package.
  • admin.py contains settings for the Django admin pages.
  • apps.py contains settings for the application configuration.
  • models.py contains a series of classes that Django’s ORM converts to database tables.
  • tests.py contains test classes.
  • views.py contains functions and classes that handle what data is displayed in the HTML templates.

Once you’ve created the app, you need to install it in your project. In mysite/settings.py, add the following line of code under INSTALLED_APPS:

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

That line of code means that your project now knows that the app you just created exists. The next step is to create a view so that you can display something to a user.

Create a View

Navigate to the views.py file in the hello_world directory. There’s already a line of code in there that imports render(). Add the following code:

from django.shortcuts import render

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

You’ve defined a view function called helloworld(). When this function is called, it will render an HTML file called hello_world.html. That file doesn’t exist yet, so let's create it. Create that directory and subsequently a file named helloworld.html inside it:

$ mkdir hello_world/templates/
$ touch hello_world/templates/hello_world.html

Add the following lines of HTML to your file:

# hello_world.html
<h1>Hello, World!</h1>

You’ve now created a function to handle your views and templates to display to the user. The final step is to hook up your URLs so that you can visit the page you’ve just created. Your project has a module called urls.py in which you need to include a URL configuration for the hello_world app. Inside mysite/urls.py, add the following:

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

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

This looks for a module called urls.py inside the hello_world application and registers any URLs defined there. Whenever you visit the root path of your URL (localhost:8000), the hello_world application’s URLs will be registered. The hello_world.urls module doesn’t exist yet, so you’ll need to create it:

$ touch hello_world/urls.py
from django.urls import path
from hello_world import views

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

Now, when you restart the server and visit localhost:8000, you should be able to see the HTML template you created:

header image

Good job!!! You’ve created your first Django app and hooked it up to your project. Now, let's run inside docker container.

Step 4: Dockerize the Application

Setup Docker

Before creating a container for the Django application and shipping it off, you need to install Docker on your local machine. For learning purpose, you will install Docker Community Edition. Select your OS from the list below and follow the setup instructions;

Make the docker App image

The next stage is to add a Dockerfile to your project. The structure of a Dockerfile can be considered a series of instructions on how to build your container/image.

Start the Dockerfile by creating an empty file named Dockerfile in the root of your project. Then, complete each instruction according to the following example:

# Dockerfile

# The first instruction is what image we want to base our container on
# We Use an official Python runtime as a parent image
FROM python:3.7

# Allows docker to cache installed dependencies between builds
COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

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

EXPOSE 8000

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

The first directive in the Dockerfile, FROM python:3.7 tells Docker which image to base our container on. We use the official Python image from Dockerhub that comes with Python and Linux setup for you, ready for use in a python project.

You are now ready to build the container image, and then run it to see it all working together.

Building and Running the Container

Building the container is very straight forward once you have Docker and Docker Machine on your system. The following command will look for your Dockerfile and download all the necessary layers required to get your container image running. Afterwards, it will run the instructions in the Dockerfile and leave you with a container that is ready to start.

To build your container, you will use the docker build command and provide a tag or a name for the container, so you can reference it later when you want to run it. The final part of the command tells Docker which directory to build from.

$ cd
$ docker build -t python-django-app .

header image

The final step is to run the container you have just built using Docker:

$ docker run -it -p 8000:8000 python-django-app

The command tells Docker to run the container and forward the exposed port 8000 to port 8000 on your local machine. After you run this command, you should be able to visit http://localhost:8000 in your browser to see the “Hello, World!” response.

You can see the Docker containers that are currently running on your system (along with their Container IDs) with:

$ docker ps -a

To turn off your Docker container, run:

$ docker stop container_id

Step 5: Push to cloud

1. Create your app

In order to install the django docker container, create a new app via cli or admin panel and set a port to 8000.

header image

2. Push your docker container

Before push the container you need to enable the URL into the django ALLOWED_HOST. So go on mysite/setting.py:

...

ALLOWED_HOSTS = [
    '<app-created-name>.on.dockerize.io'
]
...

Now just build and push the container:

$ docker login -u (login to show username) -p (login to show password) reg.dockerze.io
$ docker build -t reg.dockerze.io/(login to show username)/imagename .
$ docker push reg.dockerze.io/(login to show username)/imagename

header image

header image

3. Set up resources

header image

5. Logs and app status

header image

6. Release

header image

Now you can deploy your django app without a massive build time.

Bonus 1: SSL certificate for HTTPS

It's already done for you. If you need to connect your custom domain, SSL certificate will be provided for it.


Bonus 2: Autoscaling

With autoscaling the app will be scaled up when CPU and RAM load goes up and scaled down when it goes down.

Now you can deploy your django app without a massive build time.

Dockerize your Job

Just for $2/month
Share this article:

Ask a question

Please type your name.
Please provide your email address.
Please tell us a bit more

More great guides

Docker nodejs express tutorial

Docker NodeJS Express guide

Simple Nodejs Socket guide for docker deploy. Use it for comfort start with us.

Read Guide
Docker python django tutorial

Docker Python Django tutorial

This is a brief tutorial that presents how you can run a simple 'Hello World'-style web application written in Django in docker.

Read Guide
Docker PHP laravel tutorial

Docker PHP laravel tutorial

This quickstart guide provides a basic introduction to the Laravel framework running on docker. This is a great starting point if you are brand new to the Laravel framework or if you want to have your docker PHP app.

Read Guide
7 times faster deployment
Dockerize automaticaly completes deployment after receiving your Docker image
50% of AWS price
We don’t have any hidden prices and will never ask you to pay extra fee for our services
Open Sidebar Close Sidebar