Docker Setup

This is a basic setup. More dependencies will be added as and when needed along the project

Python requirements

Find the latest version of the required packages from PyPI

django>=2.1.3,<2.2.0
djangorestframework>=3.9.0,<3.10.0

Set up Docker image

1) Create a Dockerfile inside DjangoAPI-TravisCI-submodule

dockerfile
    FROM python:3.7-alpine
    MAINTAINER senesence

    # Ensures python output is print to the terminal
    ENV PYTHONUNBUFFERED 1

    COPY ./requirements.txt /requirements.txt
    RUN pip install -r /requirements.txt

    RUN mkdir /app
    WORKDIR /app
    COPY ./app /app

    # Create a user. -D represents this user can only run apps.
    # This is recommended. Otherwise, the image will be run from root account
    RUN adduser -D user
    # Switch to this user
    USER user

Using docker compose to build and run services

1) Docker compose is useful when we have to build and run multiple services. For eg, we may want the server and database as a different service

2) Create a docker-compose.yml file

yml
    version: "3"

    # Default image name will be djangoapi-travisci-submodule_app
    #build 'docker-compose' build from this directory
    #run 'docker-compose run app sh' 
    services:
      app:
        build:
          # path to dockerfile
          context: .
        ports:
          # map port 8000 in host machine to 8000 in container
          - "8000:8000"
        volumes:
          #synchronize app directory
          - ./app:/app
          #run server listening on all ip address on docker and map it to port 8000,
          # which is inturn forwarded to port 8000 on host machine
        command: >
          sh -c "python manage.py runserver 0.0.0.0:8000"

3) Build from directory containing .yml file

docker-compose build

4) Run. Specify the service name. Otherwise, all services will be run

a) This does not forward port

docker-compose run app sh

b) This forwards ports but does not allow logging into the container terminal or modify run command

docker-compose up app

c) To forward port and at the same time log in to the container terminal, use

docker run -it -p 8000:8000 -v PWD/app/:/app djangoapi-travisci-submodule_app sh
python manage.py runserver 0.0.0.0:8000 #requires 0.0.0.0 to be added to allowed host

5) Start docker container and create django project inside app folder. Editing them locally will be reflected in the contrainer