hackajob Insider

How to Dockerise your Django Application

Written by hackajob Staff | Nov 28, 2019 12:00:00 AM

According to most (hello r/microservices!), Microservices are the hot new thing in application architecture. So what’s the fuss? Essentially, Microservices were founded on the need to breakdown monolithic applications into services that are easier to maintain, independently deployable and loosely coupled. One of the key things to note is that each of these Microservices must be tested independently because they are standalone systems.

Docker is a containerisation platform that allows you to deploy your Microservices in containers. These containers are standalone, but can communicate with each other. Additionally, Docker containers bundle their own configuration files, software, and libraries. But why not just use a virtual machine instead of these containers? The latter are run by a singular OS kernel and are therefore more lightweight.

Note that Docker is particularly useful when scaling applications. For example, installation and onboarding for new members is especially easy when working with containers. Otherwise, the new engineer would have to install multiple databases, queuing systems, and be very keen on individual system requirements.

You might be wondering, ‘How do I dockerize my Django application?’ Well wonder no more. The first step is to install Docker on your local machine. You can check ‘https://docs.docker.com/’ for installation instructions for your operating system.

Next, you’ll need to create a Docker file at the root of your application and fill it with the following information (we’ll explain how it works in a bit):

In line 1, you’re using a pre-formatted Docker container, which already has Ubuntu installed. This docker image is obtained from the Docker hub and acts as the base for the container.

In line 2, you’ll create environment variables, whereas in line 3, you’ll be making a working directory inside your container and moving it into line 4. Lines 8, 11 and 15 are where you’ll install dependencies such as modules inside your ‘requirements.txt’ file. Finally in line 20, you’ll forward the port 8000 from Guest to Host.

You’ll now create a ‘docker-compose.yml’ file in your root folder, as shown below:

This file will contain instructions for running multiple Docker containers:

You can access the container by using the following command:

docker – compose run web bash

You’ll also be able to run it without accessing the container by using any of the following commands:

docker – compose run web python manage.py migrate

docker – compose run web python manage.py shell

docker – compose run web python manage.py test

Finally, you’ll be able to run docker via the below command:

docker – compose up

Like what you've read? Don't forget to take a peek at our other Django articles.