[PYTHON] Learn how to use Docker through building a Django + MySQL environment

Introduction

After studying ** Ruby ** and ** Rails ** at a programming school, I started touching ** Python ** and ** Django ** for personal interest, but now I'm dealing with ** Django ** The first personal impression I had when I first started was that "** (for implementing features) ** preparation before starting to write code is more difficult than Rails **".

In the future, in order to improve the efficiency of personally creating various apps and moving hands to put into practice new lessons, it is necessary to get used to the environment construction work itself, as well as ** functions. I felt that it was necessary to prepare myself to be able to concentrate on implementing and practicing what I learned **, so I decided to learn about container technology (handling).

The purpose of this article (group) is ** to learn how to use Docker through Django + MySQL environment construction **, and ** to create a Django project template that you can reuse for yourself * *is.

By following the meaning of each description as carefully as possible, I would like to aim to acquire reproducible knowledge even when dealing with different languages / frameworks. It is a memorandum by Docker beginners, but please keep in touch if you like.

Execution environment

Usage environment

- MacOS catalina 10.15.6
- Docker 19.03.8
    (- docker-desktop for Mac 2.2.0.3)
- pyenv 1.2.20

Environment to build

- Python 3.7.7
- Django 3.0.8
- MySQL 5.7.31

table of contents

  1. ** Prepare virtual environment using venv ** Use venv to prepare a specific version of Python environment. It also creates a Django project.

  2. ** Consider the description of Dockerfile ** Think about ** Docker image ** through the description in the Dockerfile.

  3. ** Consider the description of docker-compose.yml ** Create docker-compose.yml and learn about ** Docker container ** through Django and the MySQL settings that connect it.

  4. ** Edit the configuration file and execute docker-compose up ** Make various settings on the Django side and execute $ docker-compose up.

  5. ** Adjust container launch timing between dependent services ** In the previous process, ** under certain conditions, the MySQL container may not launch before the Django container and the connection may fail **. We aim to solve the problem by creating a dedicated Python file **.

  6. ** Development work ** All you have to do is focus on your development work, making changes as the situation demands.

Source code

The source code of the main related files is summarized here in advance. The description contents of each file will be explained in ** Articles by process ** mentioned above.

Dockerfile


FROM python:3.7
ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code

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

COPY . /code/

EXPOSE 8000

docker-compose.yml


version: "3"
services:
    web:
        container_name: djst_django
        build: .
        restart: always
        command: >
            bash -c "
                pip install -r requirements.txt &&
                python config/wait_for_db.py &&
                python manage.py runserver 0.0.0.0:8000
            "
        working_dir: /code
        ports: 
            - 172.0.0.1:8000:8000
        volumes:
            - .:/code
        depends_on:
            - db
    db:
        container_name: djst_mysql
        image: mysql:5.7
        restart: always
        environment: 
            MYSQL_DATABASE: $DB_NAME
            MYSQL_USER: $DB_USER
            MYSQL_PASSWORD: $DB_PASSWORD
            MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
            MYSQL_TCP_PORT: 3306
            TZ: 'Asia/Tokyo'
        volumes: 
            - ./mysql/data:/var/lib/mysql/
            - ./mysql/my.cnf:/etc/mysql/conf.d/my.cnf
        ports: 
            - 3306:3306

config/wait_for_db.py


import os
import MySQLdb
from time import sleep
from pathlib import Path

os.chdir(Path(__file__).parent)
from local_settings import DB_NAME, DB_USER, DB_PASSWORD


count_to_try = 0
LIMIT_OF_COUNT = 20 #Adjust the value as needed


def check_connection(count, limit):
    """
    docker-Compose up Runtime function for time adjustment.
    """
    try:
        conn = MySQLdb.connect(
            unix_socket = "/var/run/mysqld/mysqld.sock",
            user=DB_USER,
            passwd=DB_PASSWORD,
            host="db",
            port=3306,
            db=DB_NAME,
        )
    except MySQLdb._exceptions.OperationalError as e:
        count += 1
        print("Waiting for MySQL... (", count, "/ 20 )")
        sleep(3)
        if count < limit:
            check_connection(count, limit)
        else:
            print(e)
            print("Failed to connect mySQL.")
    else:
        print("Connected!\n")
        conn.close()
        exit()


if __name__ == "__main__":
    check_connection(count_to_try, LIMIT_OF_COUNT)

If you have any suggestions, I would appreciate it if you could comment. I look forward to working with you.

Recommended Posts

Learn how to use Docker through building a Django + MySQL environment
How to build a Django (python) environment on docker
How to use tensorflow under docker environment
How to run a Django application on a Docker container (development and production environment)
[Django] Use VS Code + Remote Containers to quickly build a Django container (Docker) development environment.
How to use Docker to containerize your application and how to use Docker Compose to run your application in a development environment
How to use Mysql in python
How to delete a Docker container
How to use jupyter notebook without polluting your environment with Docker
How to build a sphinx translation environment
How to create an NVIDIA Docker environment
Learn the flow of Bayesian estimation and how to use Pystan through a simple regression model
Use WebDAV in a Portable Docker environment
A simple example of how to use ArgumentParser
How to share a virtual environment [About requirements.txt]
How to create a Python virtual environment (venv)
Build a Django environment on Raspberry Pi (MySQL)
How to develop a cart app with Django
How to reflect ImageField in Django + Docker (pillow)
[Python] Build a Django development environment with Docker
How to use pip3 under proxy environment Note
[Note] How to create a Ruby development environment
Problems connecting to MySQL from Docker environment (Debian)
How to create a Rest Api in Django
Flutter in Docker-How to build and use a Flutter development environment inside a Docker container
A memo to create a virtual environment (venv) before Django
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
[Python] [Django] How to use ChoiceField and how to add options
How to use Seaboan
How to use image-match
How to use shogun
A memo of how to use AIST supercomputer ABCI
How to use Pandas 2
How to set up a Python environment using pyenv
How to use Virtualenv
Building a Docker working environment for R and Python
How to use numpy.vectorize
How to deploy a Django application on Alibaba Cloud
How to use pytest_report_header
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
A memorandum on how to use keras.preprocessing.image in Keras
How to use fixture in Django to populate sample data associated with a user model
How to use partial
How to use Bio.Phylo
How to hold a hands-on seminar using Jupyter using docker
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use bootstrap in Django generic class view
How to use virtualenv
How to use Matplotlib
Build a Python virtual environment using venv (Django + MySQL ①)
How to use iptables
How to use TokyoTechFes2015
How to use dictionary {}
How to use Pyenv
How to build a development environment for TensorFlow (1.0.0) (Mac)
How to use jupyter lab in Windows 10 local environment
How to use list []