How To Guides

How to Dockerize a Django Application: Step-by-Step Guide

Dockerizing a Django application using Docker Compose to create a consistent development environment.

Are you looking to containerize your Django application using Docker? Dockerization makes deploying, scaling, and managing your app easier, offering consistent environments across different systems. In this comprehensive guide, we’ll walk you through the entire process of Dockerizing your Django application, from setting up Docker to running your app in containers.

What is Docker and Why Should You Use It for Django?

Docker is a platform that allows you to develop, ship, and run applications inside containers. These containers are lightweight, portable, and ensure that your application will run the same way, regardless of where it’s deployed. For Django developers, Docker is a great way to containerize your application and simplify deployment and scaling in different environments.

With Docker, you can:

  • Create reproducible environments.
  • Ensure consistency across different development, staging, and production environments.
  • Easily deploy and scale your Django applications.

In this guide, we’ll show you how to Dockerize your Django application, step by step.

Step 1: Install Docker Desktop

Before you begin Dockerizing your Django app, you need to install Docker on your local machine.

  1. Download Docker Desktop: Go to the official Docker website and download Docker Desktop for your operating system (Windows or macOS).

  2. Install Docker: After downloading, run the installer and follow the on-screen instructions.

  3. Verify Installation: Once Docker is installed, make sure it’s running. You can verify this by checking the system tray (Windows) or the menu bar (macOS). You should see the Docker logo indicating it's active.

Step 2: Configure Your Django App for Docker

Before we move on to Dockerizing the app, we need to make some changes to your Django project to ensure it works seamlessly in a Dockerized environment.

  1. Activate your Virtual Environment:

    python -m venv environment source environment/bin/activate # Linux/macOS
    environment\Scripts\activate # Windows
  2. Install Required Packages: In your terminal, install the necessary packages:

    pip install whitenoise gunicorn
  3. Update settings.py:

    • Add 'whitenoise.runserver_nostatic' to INSTALLED_APPS:

      INSTALLED_APPS = [
          ...
          'whitenoise.runserver_nostatic',
          ...
      ]
    • Add WhiteNoiseMiddleware to the MIDDLEWARE list:

      MIDDLEWARE = [
          ...
          'whitenoise.middleware.WhiteNoiseMiddleware',
          ...
      ]
    • Configure static files handling:

      STATIC_URL = '/static/' 
      STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] 
      STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
    • Configure media files handling:

      MEDIA_URL = '/media/'
      MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    • Finally, add the following to your urls.py to handle media files:

      from django.conf import settings 
      from django.conf.urls.static import static 

      # Add the following line to urlpatterns
      urlpatterns = [

      ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

  4. Run collectstatic: Run the Django management command to collect static files into a single location:

    python manage.py collectstatic

Step 3: Create a requirements.txt File

For Docker to install all necessary dependencies, we need to create a requirements.txt file containing all the packages used in your Django project.

  1. Generate the requirements.txt File: Before creating the requirements.txt file, make sure your environment is activated, then run this command.

    pip freeze > requirements.txt

Step 4: Write Your Dockerfile

Now that your project is configured for Docker, the next step is to create a Dockerfile. This file will contain all the instructions for building your Docker image.

Here’s a simple Dockerfile:

# Use the official Python image as a base
FROM python:3.11-bookworm

# Prevents Python from writing .pyc files to disk
ENV PYTHONUNBUFFERED=1

# Set the working directory inside the container
WORKDIR /django

# Copy the requirements.txt and install dependencies
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

# Copy the rest of the project files into the container
COPY . .

# Expose port 8000 for the Gunicorn application
EXPOSE 8000

# Run Gunicorn to serve the application
CMD ["gunicorn", "canteen_stores.wsgi:application", "--bind", "0.0.0.0:8000"]

Step 5: Create the .dockerignore File

Just like .gitignore, the .dockerignore file tells Docker which files and directories it should ignore when building the image. This helps prevent unnecessary files from being copied into your Docker image.

Here’s a basic .dockerignore file:

__pycache__/
.vscode/
environment/

Step 6: Write the docker-compose.yml File

The docker-compose.yml file is used to define and run container Docker applications. For our django app.

Here’s an example docker-compose.yml file:

version: '3.11'
services:
  app:
    build: .
    volumes:
      - .:/django
    ports:
      - 8000:8000
    image: application:django
    container_name: app_container
    command: gunicorn canteen_stores.wsgi:application --bind 0.0.0.0:8000

Step 7: Build and Run Your Docker Containers

Once you’ve set up your Dockerfile, .dockerignore, and docker-compose.yml file, you’re ready to build and run your containers.

  1. Build the Docker Image: In your terminal, run:

    docker-compose build

After running the command, Docker Desktop will build the image according to the instructions specified in your docker-compose.yml file.

Once the build process is complete, you can view the built Docker image in the Docker Desktop under the "Images" section.

  1. Start the Containers: Now, start the containers with:

    docker-compose up

    Docker will download the necessary images, build your custom image, and start the containers for the django project. In Docker Desktop, you can verify that the Docker container has been built and is currently running.

Step 8: Access Your Application

Once the containers are up and running, open your web browser and go to:

You should see your Django app running within the Docker container!

Conclusion

Dockerizing your Django application is a great way to ensure consistent environments across various stages of your development and deployment pipeline. With Docker, you can deploy your app quickly and efficiently, knowing that it will behave the same way on any machine.

By following this guide, you’ve successfully containerized your Django application using Docker, and now you can scale, deploy, and maintain it with ease. If you have any questions or issues, feel free to leave a comment below!


Popular Tags:

Related blogs

blog-img
The Evolution of Web Design: Trends That Define 2024