Build and run a Django application using Docker compose

Build and run a Django application using Docker compose

·

9 min read

In this blog, I'll walk through the process of setting up and running a Django application using Docker Compose.

I will also "attach" or connect or link the volume of the container to our local system or machine. Volumes "mirrors" the files in the container across to the local system. So whenever we make changes to our files from our VSCode, it will also update the files in the container in real-time.

And throughout this blog I will cover setting up a GitHub repository, creating a Dockerfile, configuring Docker Compose, building Docker images, and running our application. Additionally, I'll take a peek into accessing the CLI of a container and see what it looks like.

Requirements

  • Python 3

  • Git / GitHub

  • Visual Studio Code (or any text editor of your choice)

  • pip

  • Docker

  • Docker-compose (which comes bundled with Docker installation)

  • Docker Desktop (or Docker Engine)

To check the version of Docker Compose installed on your system, you can run the following command in your terminal:

docker-compose --version

Once you've got everything above, we can get started on building something awesome!

Step #1: Create a GitHub Repository with a README file and clone this in your local machine using SSH connections

Here are the step-by-step instructions to achieve this:

  1. Create a GitHub Repository:

    • Go to GitHub.

    • Log in to your account.

    • Click on the "+" sign in the top-right corner and select "New repository."

    • Enter a name for your repository, optionally add a description, choose whether it should be public or private, and click "Create repository."

  2. Add a README file:

    • Once your repository is created, you'll be taken to the repository's page.

    • Click on the "Add README" button or manually create a README.md file by clicking "Create new file" and entering "README.md" in the file name field.

    • You can add some initial content to the README file if you'd like.

  3. Set up SSH Key:

    • If you haven't already set up an SSH key, you need to generate one. Open a terminal window on your local machine.
  4. Generate SSH Key:

    • Run the following command to generate a new SSH key. Replace <your_email@example.com> with your email address connected to your GitHub account.

        ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
      
    • Press Enter to accept the default file location and optionally enter a passphrase (recommended).

  5. Add SSH Key to SSH Agent:

    • Start the SSH agent by running the command:

        eval "$(ssh-agent -s)"
      
    • Add your SSH private key to the SSH agent:

        ssh-add ~/.ssh/id_rsa
      
  6. Add SSH Key to GitHub:

    • Copy the SSH key to your clipboard:

        cat ~/.ssh/id_rsa.pub
      
    • Go to your GitHub account settings.

    • Click on "SSH and GPG keys" in the left sidebar.

    • Click on "New SSH key" and paste your SSH key into the "Key" field.

    • Give your key a descriptive title and click "Add SSH key."

  7. Clone Repository:

    • Go to your repository on GitHub.

    • Click on the green "Code" button and make sure "SSH" is selected.

    • Copy the SSH URL provided.

    • Open a terminal window and navigate to the directory where you want to clone the repository.

    • Run the following command, replacing <repository_url> with the SSH URL you copied:

        git clone <repository_url>
      
    • This will clone the repository to your local machine.

Now you have successfully created a GitHub repository, added a README file, set up SSH keys, and cloned the repository to your local machine using SSH.

Step #2: Create a requirements.txt list

Generate a list of dependencies using:

$ pip freeze > requirements.txt
$ cat requirements.txt
asgiref==3.8.1
certifi==2024.2.2
charset-normalizer==3.3.2
Django==5.0.4
docker==7.0.0
idna==3.7
packaging==24.0
requests==2.31.0
sqlparse==0.4.4
urllib3==2.2.1

Step #3: Create a Dockerfile

What exactly is a Dockerfile? Crafting one might seem daunting initially, but think of it simply as a recipe for creating personalized Docker images.

  • Setup Docker:

    It's essential to set up Docker and Docker Desktop on your local system. For educational purposes, opt for Docker Community Edition.

  • Make the docker app image:

    The next step is to include a Dockerfile in your project. A Dockerfile can be seen as a set of steps to construct your image and later your container.

    To begin, make a new file named Dockerfile in the main directory of your project. Then, follow each step carefully, just like in the example provided.

      # Use the official Python image for an Operating System
      FROM python:3.12
    
      # Ensure Python outputs everything that's printed inside the application
      # Any errors logs sends straight to the terminal, we get the message straight away
      # 1 means non empty value
      ENV PYTHONUNBUFFERED=1
    
      # Set working directory in the container
      WORKDIR /django
    
      # Copy the requirements file into the container
      COPY requirements.txt requirements.txt
    
      # Upgrade pip
      RUN pip install --upgrade pip
      # Install Python dependencies
      RUN pip install --no-cache-dir -r requirements.txt
    
  • FROM python:3.12 - The first instruction in the Dockerfile, "FROM python:3.12," tells Docker which image to start building our container from. We're using the official Python image from Dockerhub, which already has Python and Linux set up for you, all ready to go for a Python project.

  • ENV PYTHONUNBUFFERED=1 - Python show everything it prints immediately and send any error messages directly to the screen.

  • WORKDIR /django - the working directory inside the container to a folder named 'django'.

  • COPY requirements.txt requirements.txt - the 'requirements.txt' file from your local machine into the container.

  • RUN pip install --upgrade pip - pip to the latest version.

  • RUN pip install --no-cache-dir -r requirements.txt - all the Python packages listed in 'requirements.txt' without storing any temporary files.

Step #4: Create Docker Compose file

What is Docker Compose file? With a Docker Compose file, you can list out all the services you need for your project, along with their settings and how they should talk to each other. It's like giving each container a set of instructions so they know how to work together harmoniously.

In practical terms, this means that developers can specify the services (containers) required for their application, along with their respective configurations and dependencies, within a Docker Compose file. This file serves as a blueprint or declarative representation of the application's architecture and runtime environment.

So, in simple terms, a Docker Compose file is like a manager for your services, making sure they all play nice and work together smoothly without you needing to babysit each one individually. Cool, right?

# what version of docker compose, adjust to the latest version
version: '3.8'
# here we define the services we want to run in our container
services:
  app:
# "." refers to where the Dockerfile is located
    build: .
    volumes:
    # call here the folder that resides on the OS within the container
    # "." the folders in the local machine, ":" match/mirror/link to the container folder
    # /django is the workdir from the Dockerfile
      - .:/django
    # Define ports so we can access the container
    ports:
    # Port 8000 from your computer with Port 8000 of the container
      - 8000:8000
    # name of the image
    # image: <name of app>:<tag or imageName>
    image: app:django
    container_name: sturdy_container
    # represen all of them in the service and expose it in port 8000
    command: python manage.py runserver 0.0.0.0:8000

Step #5: Build a Docker image

To build the Docker image, use the following command:

docker-compose build
  • Note that we are only building the image. There will be no container running here.

To run the container, execute the following steps:

docker-compose run --rm <imageThatYouwantToUse> django-admin startproject core .
  • docker-compose: This tells your computer to use Docker Compose, a tool for defining and running multi-container Docker applications.

  • run: This command tells Docker Compose to run a command inside a service.

  • --rm: This flag tells Docker Compose to remove the container after it exits. It helps keep things clean by getting rid of temporary containers.

  • Check out the docker-compose file command. What it all does is run the server of the Django app. With django-admin startproject core . we'll first create the app.

If you check your files now, you will see the Django app files and manage.py file:

Step #6: Run the container using Docker Compose

Then, to start all the service defined in your Docker Compose configuration and start the containerized Django app, run:

docker-compose up

When you run docker-compose up, Docker Compose reads your docker-compose.yml file, builds any necessary images, creates containers for each service, and then starts those containers.

This command is handy because it automates the process of starting your multi-container Docker applications. It handles tasks like creating networks for your services to communicate, setting up volumes, and running containers with the specified configurations.

Additionally, docker-compose up will stream the logs of all the containers to your terminal, so you can see the output from each service in real-time. It's one of the fundamental commands used when working with Docker Compose.

Go to your web browser at http://127.0.0.1:8000/ or http://localhost:8000.

  • To see what Docker containers are running on your system (with their IDs):
$ docker ps -a
  • To stop your Docker container:
$ docker stop container_id

Explore the CLI of the container

Go to Docker Desktop and find your container. Click the 3 dots button and click "Open in terminal"

you can also go here by running this command from the terminal:

docker exec -it <containerName> /bin/bash

Above you will notice that the files inside your container are the same as the ones in your local machine, it's because of volumes. They help your container talk to your computer and share files back and forth, making everything run smoothly.

And there you have it! We've successfully navigated the process of setting up and running a Django application using Docker Compose. By leveraging the power of volumes, we've ensured that our development environment stays in sync with our container, allowing for real-time updates.

Throughout this blog, we've covered essential steps like setting up a GitHub repository, crafting a Dockerfile, configuring Docker Compose, building Docker images, and running our application. We've also taken a brief look at accessing the CLI of a container, gaining a glimpse into the inner workings of our environment.

With these tools and techniques at your disposal, you're now equipped to streamline your Django development process and take your projects to new heights.


Find the GitHub repo here. I've included the errors I've encountered and how I solved it.

I trust we all learned something from this blog. If you found it helpful too, give back and show your support by clicking heart or like, share this article as a conversation starter and join my newsletter so that we can continue learning together and you won’t miss any future posts.

Thanks for reading until the end! If you have any questions or feedback, feel free to leave a comment.

Did you find this article valuable?

Support anj by becoming a sponsor. Any amount is appreciated!