Django Dockerizing App
How to setup a Django project to run in Docker
This page explains how to Dockerize a Django application with ease. For newcomers, Django is a leading web framework crafted in Python and Docker is a virtualization software used to isolate the execution of a service or product using virtual containers.

Adding Docker

First of all, make sure you have Docker installed and running on your machine. Refer to the official documentation and follow the steps.
Once it's done, create a Dockerfile file. This will contains all the commands that could be called on the command line to create an image.
1
# pull official base image
2
FROM python:3.9.5-slim-buster
3
​
4
# set work directory
5
WORKDIR /usr/src/app
6
​
7
# set environment variables
8
ENV PYTHONDONTWRITEBYTECODE 1
9
ENV PYTHONUNBUFFERED 1
10
​
11
# install psycopg2 dependencies
12
RUN apt-get update \
13
&& apt-get -y install netcat gcc \
14
&& apt-get clean
15
​
16
# install python dependencies
17
RUN pip install --upgrade pip
18
COPY ./requirements.txt .
19
RUN pip install -r requirements.txt
20
​
21
# copy project
22
COPY . .
23
​
24
CMD [ "python", "manage.py migrate" ]
25
CMD [ "python", "manage.py runserver 0.0.0.0:5000" ]
26
​
27
# Exposing default running port
28
EXPOSE 5000
Copied!
Once this is done, we can build the image and run it.
1
$ docker build -t django_app .
2
$ docker run -p 5000:3000 django_app
Copied!
You can now access your app on localhost:5000.

Adding Docker Compose

If you want to create multiple images and run them using the precedent Docker configuration, you'll have to create multiple Dockerfile.
Docker Compose saves from this by allowing you to use a YAML file to operate multi-container applications at once and run it just with one command.
Follow the official documentation to install docker-compose on your machine.
Once it's done, create a docker-compose.yml file at the root of your project. Make sure to have an .env file at the root of your project.
1
version: '3.8'
2
​
3
services:
4
django-app: # The name of your application
5
build: ./
6
command: >
7
sh -c "python manage.py migrate &&
8
python manage.py runserver 0.0.0.0:5000"
9
volumes:
10
- ./:/usr/src/app/
11
ports:
12
- 5000:5000
13
env_file:
14
- ./.env
Copied!
We can now remove some lines from the Dockerfile.
1
​
2
CMD [ "python", "manage.py migrate" ]
3
CMD [ "python", "manage.py runserver 0.0.0.0:5000" ]
4
​
5
# Exposing default running port
6
EXPOSE 5000
Copied!
And now let's use docker-compose command to build and run the image.
1
docker-compose up --build
Copied!
And your application will be running on localhost:5000.

Dockerize a production-ready app

@please refer to the configuration implemented by the reference Django Codebase​
    Django App
      short info regarding the codebase
    Gunicorn - the WSGI server
    Nginx - a powerful HTTP proxy
    Dockerfile
      How to bundle the information
    Docker-compose
​
Last modified 26d ago