/ Django

Containerize Django application using Docker

Here I am not going to talk about why use docker? Difference between VM and docker? and bla bla bla. There are a lots of article available on internet about it. Here I am going to talk about how we can dockerize Django application using Dockerfile. If you have not installed Docker in your machine please find installation steps here. All source code will be found in GitHub.

Create Dockerfile

With docker set up on your local machine, create a file in your project root directory named Dockerfile The Dockerfile will containt a set of instrations about how docker will build a conainer image from your application.

FROM python:3.6.7

# Set PYTHONUNBUFFERED so output is displayed in the Docker log

# Copy the rest of the applicaion's code
COPY . /usr/src/app

WORKDIR /usr/src/app

# Install dependencies
RUN pip install -r requirements.txt

# Run the app
CMD ["./run_app.sh"]


The first line of Dockerfile FROM python:3.6.7 tells Docker which will be the base image for our container. We can build from scratch or use existing image. For our Django application we will use python official image from DockerHub that comes with Linux and Python setup for you and ready to use python and django project.

ENV PYTHONUNBUFFERED=1 tells the docker to send the python output straight to the terminal rather than buffer in the standared output buffer.

COPY . /usr/src/app will copy the source to the docker container at location /usr/src/app

The directory starts with WORKDIR will set as working directory all the command of the following Dockerfile will execute in this directory.

The RUN keyword instracts docker to execute whatever command comes after it. As if you are executing the command in a terminal on the server.

RUN pip install -r requirements.txt tells docker to install the requirements listed in the requirements.txt file.

ENTRYPOINT configures a container that will run as an executable. The command after it will execute everytime you run the docker image.
ENTRYPOINT ["./run_app.sh"] tells docker to run our django application run script everytime we run our docker image. The run script for our django appliction is

#!/usr/bin/env bash

python manage.py migrate && python manage.py runserver

Now everytime you run the docker image it will start your django application. But you will not be able to access it untill you expose the applition port.

EXPOSE 8000 will expose the 8000 port as django default port.

We are done the Dockerfile. Now time to build your docker image. You can do it by running a simple command in the project root directory

docker build . -t shuzasa/django_learn:v1.0

After successfully creating your image you will see something like this
ckeck your image by running docker images command
Last step is to run your application by

docker run -p 8000:8000 shuza/learn_django:v1.0

Congratulation your application is up and running 😀