Now we are going to learn about how to establish Django Application in inside the Docker Container. Docker is basically a toolkit that permit developers to build, deploy, run, update, and stop containers using simple and easy commands and work-saving.

First we have to create the Docker file in the Project root. Create a file name: Dockerfile using any editor like vim or vi or nano and etc. And copy the lines below,


# syntax=docker/dockerfile:1
FROM python:3.9-alpine
WORKDIR /app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install psycopg2 dependencies
RUN apk update \
&& apk add postgresql-dev gcc python3-dev musl-dev

# install dependencies
COPY requirements.txt /app/requirements.txt
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

# copy project
COPY . .
EXPOSE 3000
CMD ["python", "manage.py", "runserver", "0.0.0.0:3000"]

Using the simple docker commands will build and deploy the application in your local machine in any cloud instance.

Build the docker image with a Dockerfile,

$ docker build t python-hello .


The . (dot) is pointing to the current location. Next make sure that docker image is available using the command,

$ docker image ls


$ docker run -itd –name python-python -p 3000:3000 python-hello:latest


Once you have executed the above command, make sure that the Django application is running or not,

‚Äč$ docker container ls -a


or

Jump into the running container,

$ docker container exec -it  python-python bash 


Open the browser and refresh the page with the URL: http://localhost:3000