Codong's Development Diary RSS 태그 관리 글쓰기 방명록
2022-12-25 22:05:55

개요

도커를 이용해서 mysql db를 사용하는 django project를 만들고 싶었다.

도커만 설치하면 어디서든 쉽게 실행시킬 수 있다는 장점이 넘 달달하죠잉~🍯



본문

1. docker compose 세팅

대충 나는 아래와 같이 기본적인 것만 해뒀다.

# docker-compose.yml
services:
  db:
    image: mysql:5.7
    container_name: example
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: "test"
      MYSQL_USER: "root"
      MYSQL_ROOT_PASSWORD: "test1234"
    volumes:
      - ./mysql:/var/lib/mysql:rw
      - ./docker/mysql/conf.d:/etc/mysql/mysql.conf.d:ro # mysql setting 적용을 위함.

맨 아랫줄은 mysql setting 값들을 파일로 적용시키기 위함이다. 아래 사진 참고.

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


2. DB 생성 확인

~ ❯ docker exec -it drf-example /bin/bash
root@937526738ea0:/# mysql -u root -ptest1234
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.38-log MySQL Community Server (GPL)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

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 |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.07 sec)

mysql>

원했던 대로 test db가 잘 생성되어있는 것을 확인할 수 있다.


3. django config

DATABASES = {
    'default' : {
        "ENGINE": "django.db.backends.mysql",
        'NAME': 'test',
        'USER': 'root',
        'PASSWORD': 'test1234',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

4. django 서버 실행

~/drf_example ❯ python manage.py runserver
...
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")

뜬금없이 socket 파일을 못 찾는다 ㅇㅈㄹ 너무 화가 남.... 이거 때문에 조금 시간을 허비했다....

구글링 결과 알고 보니 django settings 파일에 db host 값을 localhost라 하면 django가 db 통신을 tcp로 하는 게 아닌 소켓으로 해버린단다...

ref. https://stackoverflow.com/questions/58029324/2002-cant-connect-to-local-mysql-server-through-socket-run-mysqld-mysqld-so

host 값을 '127.0.0.1'로 바꾸면 아주 가뿐하게 실행된다~~