How To Deploy Django Using Docker Compose On Windows In 9 Steps

Viktor Nagornyy
Powered by Django
Published in
8 min readMar 22, 2023

Deploying Django using Docker Compose is a great way to create a local development environment without installing everything on your computer. This also allows you to create variations of packages, versions, and settings.

The following instructions are for beginners. You're in the right place if you haven’t used Django and Docker before.

The instructions will help you set everything up, more specifically:

  • Install Docker for Windows
  • Create Dockerfile
  • Create docker-compose.yml to use Docker Compose (v2)
  • Use the Django Environ package to manage environment variables
  • Deploy containerized Django 4.1 with Postgresql database

Before we begin

Let’s get a few things set up before we start:

Visual Studio Code

I recommend you install and use Visual Studio Code (VS Code) as your editor for this article. You can use any other code editor, but the instructions will use VS Code.

We will use the built-in command prompt (CMD) terminal inside VS Code.

Command prompt terminal inside VS Code

To open the CMD terminal in VS Code (refer to the image above):

  1. Click on Terminal at the top of VS Code.
  2. Find and click on New Terminal in the dropdown menu.
  3. Once the terminal is open, make sure it says CMD. If not, click on the plus sign with the dropdown.
  4. Select “Command Prompt” from the menu.
  5. Your CMD terminal is open now.

Docker for Windows

You must install Docker For Windows to run Docker containers on your Windows PC. Once installed, it includes Docker Compose v2.

Note: We will use docker compose v2 commands, not docker-compose v1.

Once everything is set up and ready, we can get started!

Step 1: Create a new directory for your project

In the CMD terminal, navigate to the directory where you want to create your new Django project. Then run the following command to create a new directory for your project. This is where everything will be kept:

mkdir myproject

Replace “myproject” with the desired project name. Then, navigate to the newly created project directory:

cd myproject

Step 2: Create the Dockerfile

A Dockerfile is a text-based script containing a set of instructions used to create a Docker image. It’s a blueprint for building containerized apps.

The Dockerfile specifies the base image, dependencies, environment variables, and other configurations required for the application to run properly within a Docker container.

Using a Dockerfile, developers can create consistent, reproducible, and portable environments, making deploying and managing applications across different platforms and systems easier.

Let’s create Dockerfile for your Django project. You must create a new file using VS Code:

  1. File › New File
  2. Type in the name of the file: Dockerfile (no extensions)
  3. Save it inside your “myproject” directory (this is important).

Once the file is saved and open in VS Code, let’s add the following:

# Use the official Python base image
FROM python:3.9

# Set the working directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY . .

# Expose the port the app will run on
EXPOSE 8000

Save the contents (CTRL+S).

Step 3: Create the requirements.txt file

The requirements.txt file is a plain text file used in Python projects to list the dependencies and their specific versions required for the app to run.

This file is often used with pip Python package manager to streamline the installation process of these dependencies.

By providing a requirements.txt file, developers can ensure consistent behavior across different environments and make it easier for others to set up the app.

It also simplifies deployment, as all required packages can be installed automatically by running pip install -r requirements.txt.

Again, create a new file in VS Code and save it inside your “myproject” directory. When your requirements.txt is saved and open, add this:

Django>=4.1,<4.2
psycopg2-binary>=2.9,<3.0
django-environ>=0.7,<1.0
  • Django package installs Django.
  • psycopg2-binary is needed for the Postgresql connection.
  • django-environ will manage environment variables in settings.py.

Step 4: Create the docker-compose.yml file

Docker Compose is a tool for defining and managing multi-container Docker applications. A single file allows developers to define and configure an entire application stack, including services, networks, and volumes.

This YAML file serves as a blueprint for the application architecture, specifying how different containers interact and are connected.

Docker Compose simplifies the process of building, deploying, and managing multi-container applications, making it easier to maintain consistency across different environments.

With a single command, docker compose up, developers can launch the entire application stack as specified in the docker-compose.yml file.

This helps streamline development, testing, and deployment processes, ensuring all team members work with the same configurations and reducing potential issues arising from setup inconsistencies.

Create a new file in VS Code called docker-compose.yml and save it inside your “myproject” directory. Once open, add the following:

version: '3.9'

services:
db:
image: postgres
env_file:
- .env
web:
build: .
command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
env_file:
- .env

By specifying env_file: - .env, Docker Compose will load the environment variables from the .env file for the respective services.

This way, you can keep your docker-compose.yml file clean and free from sensitive information. This is covered in step 7.

Step 5: Create a new Django project inside the Docker container

Your Django must be set up with a new project, which creates all the necessary directories and files.

In the CMD terminal, run the following command:

docker compose run web django-admin startproject myproject /app

If you get an error: “no configuration file provided: not found”, you’re not inside your “myproject” directory where docker-compose.yml is. Navigate to the directory and execute the command again.

Step 6: Configure Django settings for Postgresql using Django Environ

Open the myproject/settings.py file in VS Code.

At the top of the file, add the following lines to add Django Environ:

import environ

env = environ.Env()
environ.Env.read_env()

This is what the settings.py should look like. Note lines 14–17:

Django settings.py

Next, we need to replace the existing DATABASES configuration with the following code to use the Postgresql database:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': env('POSTGRES_DB'),
'USER': env('POSTGRES_USER'),
'PASSWORD': env('POSTGRES_PASSWORD'),
'HOST': 'db',
'PORT': 5432,
}
}

You must delete the default DATABASES that uses sqlite database.

This is what the settings.py should look like. Note lines 80–89:

Save and close the settings.py file.

Step 7: Create .env file for environment variables

Django Environ will read the environment variables from .env file or Docker container’s environment variables. For this tutorial, we will use the popular .env file.

Create a new file in VS Code called .env and save it inside your “myproject” directory. Once open, add the following:

POSTGRES_DB=myproject_db
POSTGRES_USER=myproject_user
POSTGRES_PASSWORD=myproject_password

Replace myproject_db, myproject_user, and myproject_password with your desired database name, user, and password. For local development purposes, you can leave these values as is.

Step 8: Build and run the Docker containers

It’s time to build and run your Docker containers.

Build Docker containers

Run the following command in CMD terminal:

docker compose build

You don’t have to run this command often after the initial build process. Here’s when you need to run docker compose build:

  1. When you update the Dockerfile.
  2. When you add, remove, or update dependencies in the requirements.txt file.
  3. When you modify the application code, and the changes affect the build process or require new dependencies.
  4. When you change any files or configurations copied into the image during the build process.

However, if you are only updating the Django code and the changes don’t affect the build process or dependencies, you can skip running docker compose build and use docker compose up directly.

This is because Docker Compose automatically detects changes to the Django code and updates the running container when using bind mounts, as specified in the volumes section of the docker-compose.yml file.

In our docker-compose.yml, we use the following bind mount to map the local project directory to the /app directory inside the Docker container, effectively syncing the application code between the host and the container.

services:
web:
...
volumes:
- .:/app
...

In this configuration, the dot (.) represents the current local project directory and /app is the target directory inside the Docker container.

Using bind mounts, any changes made to the Django code on the host system are immediately reflected inside the container, allowing for a smoother development process without rebuilding the Docker image for every change made to the Django code.

Keep in mind that bind mounts should be used cautiously in production environments, as they may introduce potential security risks and performance impacts.

Run Docker containers

Run the following command to start the Docker containers:

docker compose up -d

The -d flag in the docker compose up command is used to run the containers in detached mode.

When you run the command with the -d option, Docker Compose starts the containers in the background and returns control to the terminal or command prompt, allowing you to continue using it for other tasks.

Running the containers in detached mode is useful when you don’t want to see the logs of the running containers in the terminal or when you want to keep the containers running after closing the terminal.

If you need to access the logs of the containers running in detached mode, you can use the docker compose logs command followed by the service name like this:

docker compose logs web

If you need to stop the containers running in detached mode, use the docker compose down command.

If you want to see all running containers, use the docker ps command.

Step 9: Access the Django app

Once your containers run without issues, you can access your Django app by going to http://localhost:8000.

You should see the default Django welcome page:

Default Django welcome page

If you see the welcome page, congratulations! You’ve successfully deployed Django using Docker Compose on Windows PC.

What’s next?

Many Django packages can save time and effort if you build a product. Check out my list of popular Django packages:

New To Django?

If you’re new to Django, as I was, you may be looking for good resources to learn how to use Django to build apps. The best resources that helped me learn Django with easy-to-follow instructions and code are the three ebooks written by William S. Vincent (he keeps them up-to-date):

Django for Beginners laid a solid foundation for me to pick up all other Django (and Python) concepts. Start with that ebook. That’s what I did.

If you want to be notified of new stories related to Django, follow Powered by Django here on Medium, or you can follow me to learn more about digital marketing in addition to Django.

ChatGPT contributed to this article.

This article includes affiliate links.

--

--

Viktor Nagornyy
Powered by Django

📈 Marketing consultant. 14 years helping biz generate leads & sales. Open source advocate. Sign up for my marketing coaching newsletter ➡️ inboundmethod.com/m