🧩Javascript/node.js

NestJs 도커로 MySql 연동하기

DevJiun 2022. 3. 11. 12:34

OS: 윈도우11

 

설치된 Mysql 버전을 확인해줍니다.

$ mysql --version
mysql  Ver 8.0.28 for Win64 on x86_64 (MySQL Community Server - GPL)

저는 8.0.28 버전이 깔려있네요.

 

Docker를 설치해 줍니다.

https://www.docker.com/products/docker-desktop

 

Docker Desktop for Mac and Windows | Docker

Learn why Docker Desktop is the preferred choice for millions of developers building containerized applications. Download for Mac or Windows.

www.docker.com

도커설치는 위 링크에서 그냥 일반 프로그램 받듯이 설치해주시면 되서 쉽습니다.

 

$ docker -v
Docker version 20.10.12, build e91ed57

도커가 잘 설치 됐다면 위처럼 나옵니다.

 

설치된 도커 데스크탑을 실행한 후

 

https://hub.docker.com/_/mysql?tab=tags

위 링크에서 본인 Mysql버전에 맞는 MySQL Docker 이미지를 찾습니다.

태그에 버전을 입력하지 않으면 가장 최신 이미지가 설치됩니다.

$ docker pull mysql:8.0.28

해당 명령어로 이미지를 설치합니다.

Status: Downloaded newer image for mysql:8.0.28
docker.io/library/mysql:8.0.28

이렇게 나온다면 성공입니다.

$ docker images
REPOSITORY   TAG       IMAGE ID       CREATED      SIZE
mysql        8.0.28    826efd84393b   2 days ago   521MB

잘 설치됐는지 확인해줍니다.

 

$ docker run --name mysql-local -p 3306:3306/tcp -e MYSQL_ROOT_PASSWORD=test -d mysql:8.0.28

컨테이너 이름은 mysql-local port는 3306 패스워드는 test 이미지 버전은 8.0.28

 

$ docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS
    NAMES
9371c0ae6431   mysql:8.0.28   "docker-entrypoint.s…"   28 minutes ago   Up 28 minutes   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql-local

실행되었는지 확인해줍니다.

 

잘 실행되었다면 데이터베이스랑 연결해줍시다.

 

저는 DBeaver로 했습니다. 다른 분들은 Workbench나 본인에게 편한걸로 진행해주세요.

 

DBeaver를 실행 후 

 

 

password를 입력해줍니다.

 

public key를 등록을 허용해 줍니다.

 

$ npm i typeorm @nestjs/typeorm mysql2

nest에 mysql을 연동하기 위한 라이브러리를 설치합니다.

 

AppModule import에

TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'test',
      database: 'test',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),

위 코드를 추가해줍니다.

설정은 본인 설정에 맞게 바꿔줍니다.