It's always been a challenge for Django developers to find the easiest and most efficient way to dockerize their applications. In this article we will acknowledge this challenge and come up with a viable solution.

Step 1:

First of all, you want to head over to the official Docker website and download docker desktop for your operating system:

šŸ‘‰ https://www.docker.com/


Step 2:

Once you have downloaded docker desktop. You can proceed to start it up. Once it has started you can go ahead and explore the menu's/sections on the left, such as:

  • Containers
  • Images
  • Volumes
  • Dev environments

We will only be focusing on Containers and Images. So, once we build our docker image it will appear under the Images section, and if we run our docker container it will appear under the Containers section.


Step 3.1:

Next we will need to install Gunicorn:

šŸ‘‰ https://pypi.org/project/gunicorn/

Gunicorn is a WSGI HTTP server that is necessary to help us to dockerize our Django web app.


Step 3.2:

The next step involves generating a requirements.txt file.

To generate a requirements.txt file simply head over to your terminal and enter in the following command:

pip freeze > requirements.txt


Step 4:

The next step involves creating our Dockerfile.py file within our application:


# We need to import a python based image
FROM python:3.8-buster

# Create a working directory for our docker file
WORKDIR /djangoapp

# Sends python output to our container logs
ENV PYTHONBUFFERED=1

# Copy all of the packages that are within our requirements.txt file
COPY requirements.txt requirements.txt

# Install all of the packages that are within our requirements.txt file
RUN pip3 install -r requirements.txt

# Copy our entire project directory for our docker image
COPY . .

# To run our Django app we need to serve it with Gunicorn 

# Please note: elevate is the name of my Django project
CMD gunicorn elevate.wsgi:application --bind 0.0.0.0:8000

# Expose our docker image at port 8000
EXPOSE 8000



Step 5:

Next we will need to create a docker-compose.yml file to help us to define our container.

version: "3.8" # We need to define the docker specification version
services: # Define our service(s) - in this case we only have one 
  app: # We will build a singular app 
    build: . # Used to build our dockerfile
    volumes: # This refers to our directory that we defined /djangoapp
      - .:/djangoapp
    ports: # We want to expose port 8000 within our container
      - 8000:8000
    image: myapp:django # Tag/add our docker image name
    container_name: djangoapp_container # Specify a container name
    command: gunicorn simply.wsgi:application --bind 0.0.0.0:8000 # Expose all IP addresses to connect to port 8000



Step 6:

To build our docker image we need to run the following command within our terminal:

docker-compose build


Step 7:

To run our docker container we need to run the following command within our terminal:

docker-compose up