Friday, 29 April 2022

Set up MYSQL with Django using DockerFile and Docker-Compose

 Dockerfile (use alpine light version)

From python:3.10-alpine3.14


RUN apk update

RUN apk add --virtual build-deps gcc python3-dev musl-dev

RUN apk add --no-cache mariadb-dev


ENV PYTHONBUFFERED 1


COPY ./requirements.txt /requirements.txt


RUN pip install -r /requirements.txt


RUN apk del build-deps


RUN mkdir /app

WORKDIR /app

COPY ./app /app



RUN adduser -D appuser

USER appuser



--------------------------------

RUN apk update

RUN apk add --virtual build-deps gcc python3-dev musl-dev

RUN apk add --no-cache mariadb-dev

https://stackoverflow.com/questions/56048631/docker-alpine-error-loading-mysqldb-module

is needed to install mysqlclient in requirements.txt


https://stackoverflow.com/questions/46221063/what-is-build-deps-for-apk-add-virtual-command

--virtual means can be deleted after requried stuff requiring dependecy is installed


-----------------------------

requirements.txt

Django>=4.0.4,<4.1.0

djangorestframework>=3.13.1,<3.20.0


mysqlclient>=2.1.0<=2.2.0


flake8>=4.0.1,<4.1.0

------------------------------

docker-compose


version: "3"


services:

  app:

    user: $UID:$GID

    build:

      context: .

    ports:

      - "8000:8000"

    volumes:

      - ./app:/app

    command: >

      sh -c "python manage.py runserver 0.0.0.0:8000"

    environment:

      - DB_HOST=db

      - DB_NAME=djangodemo

      - DB_USER=mysqldjango

      - DB_PASS=mysqldjango01!

    depends_on:

      - db

  db:

    image: mysql:8

    environment:

      - MYSQL_ROOT_PASSWORD=test

      - MYSQL_USER=mysqldjango

      - MYSQL_PASSWORD=mysqldjango01!

      - MYSQL_DATABASE=djangodemo

    ports:

      - "3307:3307"


------------------------

db service enviroment variable comes from docker hub documentation 

https://hub.docker.com/_/mysql


app service enviroment vriable DB_HOST is assigned with db service

are used in pything settings.py

located by the folder created by docker-compose run app sh -c "django-admin startproject app ."

------------------

settings.py 

need

import os

DATABASES = {

    'default': {

        # 'ENGINE': 'django.db.backends.sqlite3',

        # 'NAME': BASE_DIR / 'db.sqlite3',


        'ENGINE': os.environ.get('APP_DB_ENGINE', 'django.db.backends.mysql'),

        'NAME': os.environ.get('DB_NAME', 'db.sqlite'),

        'USER': os.environ.get('DB_USER', ''),

        'PASSWORD': os.environ.get('DB_PASS', ''),

        'HOST': os.environ.get('DB_HOST', None),

        'PORT': os.environ.get('DB_PORT', None),

        'CONN_MAX_AGE': 600,

    }

}





No comments:

Post a Comment