paint-brush
How to Dockerize And Deploy Django Applications by@abrahamdahunsi
10,123 reads
10,123 reads

How to Dockerize And Deploy Django Applications

by Abraham Dahunsi October 14th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

In this tutorial, you learned how to dockerize and deploy Django applications using Docker, Django, and Heroku. You saw how Docker can help you create isolated and reproducible environments for your applications, and how Heroku can simplify the deployment process. You also learned how to use Docker Compose to manage multiple containers and services, and how to configure your Django settings for different environments.
featured image - How to Dockerize And Deploy Django Applications
Abraham Dahunsi  HackerNoon profile picture

Docker is a platform for building, running, and distributing applications. It allows you to package your application and all of its dependencies into a single container, which can then be run on any machine that has Docker installed.


This makes Docker ideal for deploying web applications, as it makes it easy to move your application from one environment to another without having to worry about any compatibility issues.


Django on the other hand, is a Python web framework that makes it easy to create powerful and scalable web applications. Django provides a number of features out of the box, such as a user authentication system, a database abstraction layer, and a template engine.


This makes it easy to get started with Django and to build complex web applications quickly and easily.


Dockerizing and deploying a Django application is a relatively straightforward process. The main steps involved are:


1. Create a Dockerfile for your Django application.

2. Build a Docker image from your Dockerfile.

3. Deploy the Docker image to a production environment.


In this article, I will walk you through the steps involved in dockerizing and deploying a Django application in detail. I will also provide some tips and best practices for deploying Django applications in production.

Prerequisites

To follow this tutorial, you will need the following prerequisites:


  • Python 3.9 or greater
  • Pip
  • Docker
  • Docker Compose
  • Git


You will also need a cloud hosting provider such as AWS, Azure, or Google Cloud Platform if you want to deploy your Django application to production. But for this tutorial, I will be using Heroku.


Once you have all of the prerequisites installed, you are ready to start Dockerizing and deploying your Django application!

Creating a Django Project

To start a new Django project, you need to use the django-admin command. This command lets you create a project directory and some basic files for your Django application. For example, if you want to create a project called my_project, you can run this command in your terminal:


django-admin startproject my_project


This will create a directory called `my_project` with the following structure:



my_project/


├── manage.py


└── project/


├── init.py


├── settings.py


└── urls.py


The manage.py file is a script that allows you to perform various tasks for your project, such as running the development server, creating database migrations, and testing your code. The project/ directory contains the settings and configuration files for your project.


The settings.py file defines the main settings for your project, such as the database connection, the installed apps, and the middleware. The urls.py file maps the URLs of your project to the views of your apps.


After creating a new Django project, you can test it locally by running the development server. The development server is a simple web server that runs on your machine and serves your project files. To start the development server, run this command in your terminal:


python manage.py runserver


This will start the server on port 8000 by default. You can then open your browser and go to http://localhost:8000/ to see the default Django homepage.

Basic Structure and Files of a Django Project

A Django project is composed of several files and directories that define the functionality and appearance of your web application. The main components of a Django project are:


manage.py: A script that provides various commands for managing your project, such as creating apps, migrating the database, and testing your code.


project/: A directory that contains the settings and configuration files for your project. The main files in this directory are:

`settings.py`: A file that defines the main settings for your project, such as the database connection, the installed apps, and the middleware. You can customize this file to suit your needs and preferences.

`urls.py`: A file that maps the URLs of your project to the views of your apps. You can define different URL patterns for different parts of your web application.


apps/: A directory that contains all of the Django apps that make up your project. Each Django app is a separate Python package that provides a specific functionality or feature for your web application. You can create your own apps or use existing ones from third-party sources.

Testing the Project Locally

To test the project locally, you can use the development server or the testing framework provided by Django. The development server is a simple web server that runs on your machine and serves your project files. The testing framework is a tool that allows you to write and run unit tests for your code.


To use the development server, you can run this command in your terminal:


python manage.py runserver


This will start the server on port 8000 by default. You can then open your browser, and go to `http://localhost:8000/` to see the default Django homepage.


To use the testing framework, you can run this command in your terminal:


python manage.py test


This will run all of the unit tests for your project. If all of the tests pass, you will see a message like this:



Ran 1 test in 0.001s
Ok


If any of the tests fail, you will see an error message with details about the failure. You can use this information to debug and fix your code.


Once you have tested the project locally and are satisfied with the results, you can deploy it to a production environment.

Dockerizing the Django Project

What Is a Dockerfile?

A Dockerfile is a text file that contains instructions on how to build a Docker image. A Docker image is a self-contained executable package that includes everything needed to run an application: code, runtime, system tools, system libraries, and settings.


To create a Dockerfile, you need to specify the base image, the commands to run to install the required packages, and the commands to run to start the application.

Example Dockerfile for a Django Project

Here is an example Dockerfile for a Django project:


FROM python:3.9

#Install Django and other required packages
RUN pip install django

# Copy the Django project files into the image
COPY ./app

# Set the working directory
WORKDIR /app

# Start the Django development server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]



This Dockerfile will build a Docker image that contains Python 3.9, Django, and the Django project files. The image will be configured to start the Django development server on port 8000.

What Is a docker-compose.yml File?

A docker-compose.yml file is a YAML file that defines the services that make up a Dockerized application. A service can be a single Docker container or a group of Docker containers.


To create a docker-compose.yml file for a Django project, you need to define the web service and the database service. The web service will run the Django application, and the database service will run the database that the Django application uses.

Example docker-compose.yml file for a Django Project

Here is an example docker-compose.yml file for a Django project:


version: "3.9"

services:
 web:
 build:
 ports:
  -"8000:8000"
 volumes
  -./:/app


 db:
  image: postgres:14.0-alpine
  volumes:
   -./postgres:/var/lib/postgresql/data



This docker-compose.yml file defines two services: web and db. The web service will build the Docker image from the Dockerfile that we created in the previous section. The web service will also expose port 8000 on the host machine so that we can access the Django development server.


The db service will use the official PostgreSQL Docker image. The db service will also mount the postgres directory on the host machine to the /var/lib/postgresql/data directory inside the container. This will ensure that the database files are persisted between container restarts.

Building and Running the Docker Containers

To build and run the Docker containers, we can use the following command:


docker-compose up -d


This command will build the Docker images for the `web` and `db` services if they do not already exist. The command will then start the Docker containers for the `web` and `db` services.

Testing the Dockerized Django Project Locally

Once the Docker containers are running, we can test the Dockerized Django project locally using a web browser. Open a web browser, and navigate to `http://localhost:8000`. You should now be able to see the Django development page.


You can also log in to the Django admin page at http://localhost:8000/admin/. The username and password are admin and admin by default.

Deploying the Django Project

Now, it's time to deploy your Django project to a cloud platform using Git, GitHub, and Heroku. You will also test your deployed web application using a web browser.

What Is Git, and Why Do We Need It?

Git is a software tool that can help you manage the source code of your project. It allows you to track the changes made to your code, collaborate with other developers, and revert to previous versions if something goes wrong.


Git can also allow you to push your code to remote repositories, such as GitHub, where you can store and share your code with others.

How to Create a GitHub Repository and Push Our Code to GitHub?

Please ignore the following if you have already created a GitHub repository.


To create a GitHub repository for your Django project, you need to follow these steps:


- Create a free account on GitHub


- Go to your profile page, and click on the New button next to Repositories.


- Give your repository a name, such as django-docker-app, and optionally add a description.


- Click on the Create repository button.


Now that you have created an empty repository on GitHub. To push your code to this repository, you need to use the `git` command in your terminal. I assume that you have already installed Git on your local machine and initialized a Git repository in your Django project folder. If not, follow the Official documentation to do so.


To push your code to GitHub, you need to follow these steps:


- Go to your Django project folder in the terminal, and type git status to see the current state of your repository. You should see something like this:


On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   Dockerfile
        modified:   docker-compose.yml
        modified:   requirements.txt

no changes added to commit (use "git add" and/or "git commit -a")


This means that you have some modified files that are not staged for commit. To stage them for commit, you need to use the git add command.


- Type git add . to stage all the modified files for commit. Alternatively, you can specify the file names that we want to stage, such as git add Dockerfile docker-compose.yml requirements.txt.


- Type git status again to see the updated state of our repository. You should see something like this:


On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
      modified:   Dockerfile
      modified:   docker-compose.yml
      modified:   requirements.txt


This means that you have some changes that are staged for commit. To commit them, you need to use the git commit command.


- Type git commit -m "Add Docker configuration files" to commit the staged changes with a message describing what we did. Alternatively, you can omit the -m flag and enter a longer message in an editor that will open after typing git commit.


- Type git status again to see the final state of our repository. You should see something like this:


On branch main 
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean


This means that you have one commit that is not pushed to the remote repository yet. To push it, you need to use the git push command.


- Type git push origin main to push your local commit to the remote repository on GitHub.


Alternatively, you can specify the remote name and branch name that you want to push, such as git push origin main.


You may be asked to enter your GitHub username and password or use a personal access token to authenticate yourself.


- Go to your GitHub repository page, and refresh it. You should see your code and commit message on the page.


You have successfully pushed your code to GitHub. Now, you can move on to the next step, which is deploying your Django project to Heroku.

What Is Heroku, and Why Do You Need It?

Heroku is a cloud platform that allows you to deploy, manage, and scale web applications. It supports various programming languages, frameworks, and databases, such as Python, Django, and PostgreSQL.


It also provides various features and add-ons that enhance our web development experience, such as logging, monitoring, caching, security, etc.


You need Heroku because it makes your deployment process easier and faster. You can use Heroku to deploy your Django project without worrying about the underlying infrastructure, such as servers, networks, or operating systems.


You can also use Heroku to scale your web application according to the traffic and demand. Heroku handles all the complexities and challenges of web deployment for you.

How to Create a Heroku Account and Install the Heroku CLI Tool?

To create a Heroku account, you need to follow these steps:


- Go to Heroku and click on the Signup button.

- Fill in the required information, such as name, email, password, etc.

- Choose a primary development language, such as Python.

- Click on the Create Free Account button.

- Check our email and click on the link to verify our account.


Now, you have created a free Heroku account. To install the Heroku CLI tool, you need to follow these steps:


- Go to [Heroku CLI, and choose the appropriate installer for our operating system, such as Windows, Mac OS X, or Linux.


- Download and run the installer and follow the instructions on the screen.


- Open a terminal, and type heroku --version to verify that the installation was successful. You should see something like this:


heroku/7.59.0 win32-x64 node-v12.21.0


Now, you have installed the Heroku CLI tool on your local machine. You can use this tool to interact with Heroku from the terminal.

How to Create a Heroku App and Configure the Required Settings?

To create a Heroku app for our Django project, we need to follow these steps:


- Go to your Django project folder in the terminal and type heroku login to log in to your Heroku account using the Heroku CLI tool. You may be asked to enter your email and password or use a web browser to authenticate yourself.


- Type heroku create django-docker-app to create a new Heroku app with the name django-docker-app. Alternatively, you can omit the name and let Heroku generate a random name for you. You should see something like this:


Creating ⬢ django-docker-app... done
https://django-docker-app.herokuapp.com/ | 
https://git.heroku.com/django-docker-app.git


This means that you have created a new Heroku app with a web URL and a Git URL. The web URL is where you can access your deployed web application, and the Git URL is where you can push your code to Heroku.


- Type heroku config:set SECRET_KEY=<your_secret_key> to set an environment variable for the SECRET_KEY setting of our Django project. You need to replace <your_secret_key> with a random string that you can generate using a tool like Django Secret Key Generator.


Alternatively, you can use the existing secret key that you have in your settings.py file, but this is not recommended for security reasons.


- Type heroku addons:create heroku-postgresql:hobby-dev to add a free PostgreSQL database add-on to your Heroku app. This will create a new database for your Django project and set an environment variable for the DATABASE_URL setting of your Django project. You should see something like this:

Creating heroku-postgresql:hobby-dev on ⬢ django-docker-app... free
Database has been created and is available
 ! This database is empty. If upgrading, you can transfer
 ! data from another database with pg:copy
Created postgresql-curved-12345 as DATABASE_URL
Use heroku addons:docs heroku-postgresql to view documentation


This means that you have added a PostgreSQL database add-on with the name PostgreSQL-curved-12345 and the URL DATABASE_URL.


- Type heroku config to see the list of environment variables that you have set for your Heroku app. You should see something like this:


=== django-docker-app Config Vars
DATABASE_URL: postgres://<username>:
<password>@<host>:<port>/<database>
SECRET_KEY: <your_secret_key>


This means that you have two environment variables, DATABASE_URL and SECRET_KEY, that you can use in your Django project settings.


Now that you have created a Heroku app and configured the required settings for our Django project, you can move on to the next step, which is deploying your Django project to Heroku.


How to deploy your Django project to Heroku using the `heroku` command?


To deploy our Django project to Heroku using the heroku command, you need to follow these steps:


- Go to your Django project folder in the terminal, and type heroku container:login to log in to the Heroku Container Registry using the Heroku CLI tool. This will allow you to push our Docker image to Heroku.


- Type heroku container:push web -a django-docker-app to build and push your Docker image to Heroku. You need to specify the name of your Heroku app, which is django-docker-app in this case. You should see something like this:


=== Building web (Dockerfile)
Sending build context to Docker daemon  1.024kB
Step 1/9 : FROM python:3.9-slim
---> 7f5b6ccd03e9
Step 2/9 : ENV PYTHONUNBUFFERED 1
 ---> Using cache
 ---> 64b5d0e40a22
Step 3/9 : RUN mkdir /code
 ---> Using cache
 ---> 4d8c638f2b6c
Step 4/9 : WORKDIR /code
 ---> Using cache
 ---> e69c02a028cd
Step 5/9 : COPY requirements.txt /code/
 ---> Using cache
---> 8f0f3e0f2d8c
Step 6/9 : RUN pip install -r requirements.txt
---> Using cache
---> 0f7b497d81ed
Step 7/9 : COPY . /code/
---> Using cache
---> c0a8e9a32b16
Step 8/9 : EXPOSE 8000
 ---> Using cache
 ---> a1d36a4a2da4
Step 9/9 : CMD ["gunicorn", "django_docker.wsgi", "--bind", "0.0.0.0:8000"]
 ---> Using cache
 ---> f7f3c0418a1d
Successfully built f7f3c0418a1d
Successfully tagged registry.heroku.com/django-docker-app/web:latest
=== Pushing web (Dockerfile)
The push refers to repository 
[registry.heroku.com/django-docker-app/web]
f7f3c0418a1d: Pushed 
latest: digest: 
sha256:6cbbf22cf6aa60e0343e6d8e7c4c2eeb2e
cb8fd5e82a42dfe5f4aeeb15af89ec size: 528
Your image has been successfully pushed. You can now release it with the 'container:release' command.


This means that you have built and pushed your Docker image to Heroku.


- Type heroku container:release web -a django-docker-app to release our Docker image to our Heroku app. You should see something like this:


Releasing images web to django-docker-app... done


This means that you have released your Docker image to your Heroku app.


- Type heroku run python manage.py migrate -a django-docker-app to run the database migrations on your Heroku app. This will create the necessary tables and indexes for your Django project on the PostgreSQL database. You should see something like this:


Running python manage.py migrate on ⬢ django-docker-app... up, run.1234 (Free)
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, polls
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying polls.0001_initial... OK
  Applying sessions.0001_initial... OK


This means that you have run the database migrations on your Heroku app.


- Type heroku open -a django-docker-app to open your deployed web application in a web browser. You should see your Django project running on Heroku.


You have successfully deployed your Django project to Heroku using the heroku command. You can now enjoy your web application and share it with others.

Conclusion

In this tutorial, you learned how to dockerize and deploy Django applications using Docker, Django, and Heroku. You saw how Docker can help you create isolated and reproducible environments for your applications, and how Heroku can simplify the deployment process.


You also learned how to use Docker Compose to manage multiple containers and services, and how to configure your Django settings for different environments.


Dockerizing and deploying Django applications can have many benefits, such as:


- Faster development and testing cycles

- Easier collaboration and sharing of code

- Consistent and reliable performance across platforms

- Scalability and flexibility of resources

- Security and isolation of dependencies


Read Next: CI/CD is essential for fast and reliable software delivery. To optimize your CI/CD pipeline for maximum efficiency, choose the right tools, streamline your workflow, use automated testing and QA, parallelize builds, use monitoring and feedback loops, perform security checks, and continuously improve your pipeline. Read More

Read Also: Everything We Learned at DockerCon 2023 Read More

Additional Resources

- Docker Documentation: The official documentation for Docker, where you can find guides, tutorials, reference materials, and more.


- Django Documentation: The official documentation for Django, where you can find topics, how-to guides, reference materials, and more.