Django In Docker

Why Run Django in Docker?

Django is a web application framework which can be used to develop full-stack web applications (using Django templates to render the front-end pages), or it can be used to develop a backend API (e.g. using the Django REST framework) which a front-end application can interact with.

Docker can help with CI (Continuous Integration) and CD (Continuous Deployment) of Django applications.

Simulating a Production Environment in Local Testing

It is easy to test a Django application locally using your local operating system (e.g. macOS) and a simple database engine (e.g. SQLite), but what if you want to run your tests in the same environment that will be used in production? As you become more advanced with Docker, you will want to use an orchestration tool like Kubernetes to run Docker containers in production. But if your production environment is not yet containerized, you can run your Django application’s tests in a simulated version of your production server environment, by using a Docker image matching your server’s operating system version. For example, if your server is running Ubuntu 18.04, you could run docker pull ubuntu:18.04 to download a Docker image for Ubuntu 18.04, and run your tests in a container built from that image. You can also download an image for the database engine you use on your production server (e.g. MySQL or PostgreSQL) with docker pull mysql or docker pull postgres.

Continuous Integration

Each time you push a commit to your remote repository (e.g. GitHub / GitLab / BitBucket), you can set up a web hook so that your tests are automatically run in a Docker container matching your production environment, using a CI tool like Travis CI, Semaphore CI, CircleCI or Jenkins.

Continuous Deployment

If you containerize your production environment, and use a container orchestration tool like Kubernetes or Docker Swarm, then you can define replica sets (sets of Docker container instances) which can be updated potentially with zero downtime by replacing each instance within a replica set with a newer instance created from a new image pulled from DockerHub which has passed CI test before being pushed to DockerHub.

Containerizing the Django Polls Application

If you are familiar with Django, then you are probably familiar with the “Polls” application, implemented in the Writing your first Django app tutorial at https://docs.djangoproject.com/en/2.1/intro/tutorial01/

This tutorial demonstrates how to run the “Polls” application in a Docker container. It also demonstrates how to add a RESTful API to the “Polls” application, so that it can be split into separate front-end and back-end applications which could run in separate Docker containers.