Django DB 로 MySQL 도커 컨테이너 를 사용하는 이유

MySQL 도커 컨테이너

Django DB 로 MySQL 도커 컨테이너 를 사용하면 향후 DB를 scale up 하거나 DB 서버를 이전하기에 편리합니다.

MySQL DB 를 도커 컨테이너 로 구동

도커 설치

도커 설치는 이전 글에 기술했던 Docker Installation 부분과 동일합니다.

패키지 설치

$ sudo apt update && sudo apt install \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common

GPG 키를 저장소에 추가

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

저장소 소스 목록 업데이트

$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

도커 패키지 확인

$ sudo apt update && sudo apt-cache search docker-ce

위의 과정이 정상적으로 진행되었다면 다음과 유사한 출력을 확인할 수 있습니다.

docker-ce-cli - Docker CLI: the open-source application container engine
docker-ce - Docker: the open-source application container engine

도커 설치

$ sudo apt install docker-ce

도커 사용자로 현재의 사용자 추가

$ sudo usermod -aG docker $USER

도커 설치를 마쳤다면 터미널을 종료하고 ssh 재접속하면 Docker-CLI 커맨드를 sudo 없이 사용할 수 있습니다.

MySQL 도커 컨테이너 구동

Docker-compose 설치

$ sudo apt install docker-compose

Docker-compose 작성

version: "3.1"
services:
  db:
    image: mysql:8.0.22
    container_name: db
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: mydb
      MYSQL_USER: myuser
      MYSQL_PASSWORD: mypass
      MYSQL_ROOT_PASSWORD: rootpass
    command:
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
    volumes:
      - /mnt/disks/disk1/mysql-data:/var/lib/mysql

mydb, myuser, mypass, rootpass 부분은 본인의 필요에 따라 적절하게 설정하면 됩니다.

MySQL 도커 컨테이너 버전은 Docker Hub 에서 검토하여 결정하면 됩니다.

volumes 부분은 mysql 데이터를 실제 저장하고자 하는 host에서의 directory를 앞부분에 써 주고, /var/lib/mysql 은 그대로 두면 됩니다. Cloud instance 를 사용하고 있다면, 추가 디스크를 mount 하고 해당 위치를 지정해 주는 것도 좋습니다. 이 경우 추후 워크로드가 증가함에 따라 인스턴스 크기를 키우거나 다른 호스트로 DB를 이전하고자 하는 경우에도 편리하게 이전시킬 수 있습니다.

Docker compose 를 이용해 도커 컨테이너 구동

docker-compose.yml 파일이 위치한 디렉토리에서 다음의 명령으로 도커 컨테이너를 구동할 수 있습니다.

$ docker-compose up -d

구동이 완료되었다면 컨테이너가 잘 동작하고 있는지 확인해 봅니다.

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
e326a42d001b        mysql:8.0.22        "docker-entrypoint.s…"   31 minutes ago      Up 31 minutes       0.0.0.0:3306->3306/tcp, 33060/tcp   db
$ 

MySQL 도커 컨테이너에 접속 확인

컨테이너 주소 확인

$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000
    link/ether 06:c5:16:e8:ab:26 brd ff:ff:ff:ff:ff:ff
    inet 172.31.33.233/20 brd 172.31.47.255 scope global dynamic ens5
       valid_lft 2324sec preferred_lft 2324sec
    inet6 fe80::4c5:16ff:fee8:ab26/64 scope link
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:b8:a3:75:73 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
4: br-5c841af3479f: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:c0:3f:96:2b brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.1/16 brd 172.18.255.255 scope global br-5c841af3479f
       valid_lft forever preferred_lft forever
    inet6 fe80::42:c0ff:fe3f:962b/64 scope link
       valid_lft forever preferred_lft forever
18: vethc62d2de@if17: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-5c841af3479f state UP group default
    link/ether d6:a9:05:6b:06:a3 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet6 fe80::d4a9:5ff:fe6b:6a3/64 scope link
       valid_lft forever preferred_lft forever

docker0 디바이스를 확인하면 됩니다. 별도 설정을 따로 하지 않았다면 172.17.0.1 IP 주소를 갖고 있을 것입니다.

MySQL client 설치

$ sudo apt install mysql-client-8.0

MySQL 접속 시험

앞서 확인했던 docker network host IP주소와 컨테이너 구동시 입력했던 ID/Password 를 이용해서 로그인해 봅니다.

$ mysql -h 172.17.0.1 -u myuser -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
+--------------------+
2 rows in set (0.01 sec)

mysql>

Django Web Application 을 호스트에서 구동

Python Django

Django MySQL pre-requisite 패키지 설치

$ sudo apt install python3-dev \
    libmysqlclient-dev \
    mysql-client-8.0

Python 가상환경 설정

가상 환경 설치

$ sudo apt install python3-venv

가상 환경 생성

$ python3 -m venv myenv

가상 환경 진입

$ source myenv/bin/activate

Python 패키지 설치

Python3-pip 설치

$ sudo apt install python3-pip

django 설치

$ pip3 install django==3.1.3

Django REST framework 설치

$ pip3 install djangorestframework==3.12.2

Django MySQL client 패키지 설치

$ pip3 install mysqlclient==2.0.1

Django Project 및 App 생성

$ django-admin.py startproject myproject
$ cd myproject
$ python3 manage.py startapp myapp

Django 프로젝트 settings.py 설정 변경

Django 프로젝트를 생성하면 [프로젝트명]/settings.py 파일이 생성됩니다. 해당 파일 내에는 프로젝트에서 사용할 데이터베이스에 대한 정보를 기술하는 부분이 있습니다.

기본값으로는 sqlite3 를 사용하도록 되어 있습니다. 이 부분을 지금까지 설정했던 MySQL 도커 컨테이너를 사용하도록 다음과 같이 설정을 변경해 줍니다.

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }
DATABASES = {
    'default' : {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'myuser',
        'PASSWORD': 'mypass',
        'HOST': '172.17.0.1',
        'PORT': '3306',
    }
}

DB migration

DB 설정까지 완료가 되었으므로 django 에서 기본적으로 설정하는 admin 도구를 위한 사용자 테이블을 migration 해 봅니다.

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

DB Migration 결과 확인

정상적으로 설정이 되었다면 migration이 성공하고 MySQL DB에 테이블이 생성되어 있을 것입니다.

MySQL docker container 에 접속해서 확인해 봅니다. 다음의 명령으로 container에서 bash 를 구동합니다.

$ docker exec -it db bash

Docker container의 bash shell 이 구동되면 mysql DB 에 접속해 봅니다.

root@e326a42d001b:/# mysql -u myuser -p

MySQL client shell 이 구동되면 앞서 생성했던 database 에 접속해서 테이블이 생성되어 있는지 확인해 봅니다.

mysql> use mydb;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_mydb             |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
10 rows in set (0.00 sec)

mysql>


Jay

Jay

S/W Engineer!!

8개의 댓글

treeniohjelmat · 2020-12-11 23:04

Hi! I’m at work browsing your blog from my new iphone!

Just wanted to say I love reading through your blog and look forward to all your posts!
Keep up the fantastic work!

nordicchoic · 2020-12-13 05:15

I was suggested this website by my cousin. I am not sure whether this
post is written by him as no one else know such detailed about my difficulty.

You’re amazing! Thanks!

kaçak casino siteleri · 2020-12-15 16:52

I value the article.Thanks Again. Fantastic.

moeve · 2022-01-18 05:06

Hi, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam feedback?
If so how do you prevent it, any plugin or anything you can suggest?
I get so much lately it’s driving me insane so any help is very much appreciated.

Snap으로 docker 설치 하기 Ubuntu 20.04 - voidint.com · 2021-06-28 19:16

[…] Django DB 로 MySQL 도커 컨테이너 사용하기 이런 글에서 말입니다… […]

답글 남기기

Avatar placeholder