• First You must need a requirements.txt file

requirements.txt

tqdm
python-dotenv
asgiref==3.8.1
Django==5.0.6
sqlparse==0.5.0
tzdata==2024.1
psycopg2==2.9.9
celery>=5.0.0
redis>=5.0.0
django-elasticsearch-dsl
django-elasticsearch-dsl-drf
elasticsearch-dsl
pillow

• Create a Docker file

Dockerfile

# Base build image
FROM python:3.10-alpine as base
ENV PYTHONUNBUFFERED 1

# Set work directory
WORKDIR /app

# Copy the current directory contents into the container at /app/
COPY . /app/

# Here we install the dependencies for the project and remove them after the build is done
# to keep the image size as small as possible.
RUN apk add --update --virtual .build-deps \\
    build-base \\
    postgresql-dev \\
    python3-dev \\
    libpq

# Install any needed packages specified in requirements.txt
RUN pip install -r /app/requirements.txt

• Create a docker-compose file

docker-compose.yml

services:
  db:
    container_name: postgres_db      # Here postgres_db is the container name
    image: postgres:latest           # image name is postgres, using the latest version
    ports:
      - "5432:5432"              # Forward the host's port 5432 to the container's port 5432
    volumes:
      - db:/var/lib/postgresql/data  # Here we are mounting the shop_db volume to the /var/lib/postgresql/data directory of the container
    env_file:
      - .env                      # Load the environment variables from the .env file

  app:
    container_name: shop_backend     # Here shop_backend is the container name
    image: app:shop_backend          # Here we are using the app:shop_backend image
    build: .                         # Here we are building the image from the current directory
    volumes:
      - .:/app                       # Here we are mounting the current directory to the /app directory of the container
    ports:
        - "8000:8000"
    command: ["python", "/app/shop/manage.py", "runserver", "0.0.0.0:8000"]   # Here we are running the runserver command of the manage.py file
    env_file:
      - .env
    depends_on:
      - db                       # Here we are specifying that the app container depends on the db container

  redis:
    image: redis:latest               # Here we are using the latest version of the redis image
    container_name: redis_cache       # Here redis_cache is the container name
    ports:
      - "6379:6379"                   # Here 6379 is the port number of the host machine and 6379 is the port number of the container

volumes:
  db:       # Here we are creating a volume named db

.env File

#docker-compose service name
DB_HOST=db

#database name
DB_NAME=postgres
DB_USER=postgres
DB_PASS=postgres

POSTGRES_DB=postgres
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres

After creating docker-compose.yml file, run the following command to build and run the project:

docker-compose up --build