Hi Fellas ! Today I will be showing you how we can dockerise a django with MySQL application. I will be explaining you what Docker and Containers are ? Why should we use docker to deploy our codes ? And at last I will be showing you how we can use docker to containerize a Django with MySQL application. So lets get started.

What is Docker ?

Docker is basically a tool through which we can easily create , deploy and run applications using containers. We can package our Software into Standardized Units for Development, Shipment and Deployment.

What are Containers ?

A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.

Why should we use Docker at all ?

As we all know developing modern applications can turn out to be cumbersome as the applications depend on some specific environment such as the Operating System, application dependencies and third party modules and softwares etc. Multiple languages, frameworks, architectures, and discontinuous interfaces between tools for each lifecycle stage creates enormous complexity. Docker simplifies and accelerates your workflow, while giving developers the freedom to innovate with their choice of tools, application stacks, and deployment environments for each project.

So basically you can develop your application on any platform with full freedom of choosing frameworks,languages and technologies, and still expect it to work on each system the exact same way until it has docker installed in it.

Now lets see how we can use Docker to containerize our django with mysql application step by step.

First thing first, you need to install Docker on your system . Based on your OS you can download your version of Docker from here and install it. For example I am using a Windows PC (unfortunately 🙁 ), so I installed Docker Desktop For Windows.

Once docker gets installed we will now start creating our django application. Here I expect from you that you will be familiar with the process of creating virtual environment and installing and setting django application. Since this tutorial is about using Docker to containerize and django application, I will not be showing you how to setup django project. Now moving forward with the assumption, we will generate requirements.txt file for our project. Use below command under your virtual environment for this.

pip freeze > requirements.txt

Once this file gets generated place this in your application’s root directory if you are not there already.

Now create a file called Dockerfile (note that there is no extension) in your application’s root directory and add below code.

# pull official base image
FROM python:3.8.3-alpine

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN apk update
RUN pip install --upgrade pip
RUN apk add python3-dev
RUN apk add gpgme-dev
RUN apk add libc-dev
RUN apk add gcc jpeg-dev zlib-dev libffi-dev freetype-dev musl-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev cairo-dev pango-dev gdk-pixbuf-dev
RUN apk add mariadb-dev
COPY ./requirements.txt .
RUN pip install -r requirements.txt

# copy project
COPY . .

Explaination :

We start by pulling official base Alpine image which is a mini version of Linux OS. We then specify our working directory inside the Alpine OS where our code will reside. Then we set environment variables for Python interpreter telling it not to generate byte codes (.pyc) of the .py files and also send python logs to containers.

Then we install some software packages that are required for our application to work properly. Please note that in Alpine we use apk add to install packages and apk update to fetch package updates.

And at last we copy our project files to our docker container.

Now we will move forward and create a new file in the application’s root directory and name it docker-compose.yml . Now add the below code in it.

version: '3.7'

services:
  db:
    image: mysql:5.7
    ports:
      - '3307:3306'
    environment:
      MYSQL_DATABASE: 'your_db_name'
      MYSQL_USER: 'your_username'
      MYSQL_PASSWORD: 'your_password'
      MYSQL_ROOT_PASSWORD: 'your_password'

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/usr/src/app/
    ports:
      - 8000:8000
    env_file:
      - ./.env.dev
    depends_on:
      - db

Here we define two services required for our application to work. Please note that we have mentioned the dependency of db service under the web service which means that before web service gets started please start my db service. Also we have mentioned environment file called .env.dev which will hold our application specific variables.

So lets create .env.dev file in the root directory now and add the below code.

DEBUG=1
SECRET_KEY=ANYTHINGYOUWANTBUTSTRONG!
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]

Now lets pull these variables in our application. Open settings.py file and modify it as below.

SECRET_KEY = os.environ.get("SECRET_KEY") 

DEBUG = int(os.environ.get("DEBUG", default=0)) 

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") 

#Databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_db_name',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'db',   # Name of the db service in docker-compose.yml
        'PORT': '3306',
    }
}

Enough of the configuration done and now its time to actually see it building. First make sure your docker application is running and then open your command prompt and navigate to your application’s root directory and issue below command.

docker-compose build

This command will build your containers and install its dependencies mentioned. Once this gets completed successfully issue below command.

docker-compose up -d

This command will start your services and run it in background as we used -d flag.

Now here we have two options :

  1. Import SQL data if we already have some
  2. Start blank and apply migrations.

For option 1 we will use below command :

docker exec -i container_name mysql -uyour_username -pyour_password your_db_name < dump.sql

Please make sure that dump.sql file is in your application’s root directory.Also please replace the container_name with your container name. You can get your container’s name using docker ps command.

For option 2 please use below command :

docker-compose run web python manage.py migrate

Lets have a look

Once all the steps get completed successfully we can have a look on our application. So open your browser and go to localhost:8000.

Well that’s it guys ! I hope you find this post useful and for any queries related to this please comment below.


Leave a Reply

Your email address will not be published. Required fields are marked *