Doker Mysql(sequelize)

Docker MySQL Express 연결하기

이전 도커로 express앱을 띄운 후 연결 확인 후 데이터 베이스를 도커로 실행 한 후 express와 연결하는 테스트를 진행해보도록 하자.

먼저 docker-compose.yml에 mysql이미지를 추가해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mysql:
image: mysql:5.7
command:
--default-authentication-plugin=mysql_native_password
--character-set-server=utf8mb4
--collation-server=utf8mb4_unicode_ci
restart: always
environment:
MYSQL_DATABASE: # Database Name
MYSQL_USER: # User name
MYSQL_PASSWORD: # Password
MYSQL_ROOT_PASSWORD: # Root Password
ports:
- "3306:3306"
volumes:
- ./data:/var/lib/mysql
- ./mysql.conf:/etc/mysql/conf.d

docker-compose up 명령 실행 후 mysql이 실행중인 것을 확인하고 docker exec -it #{name} bash 를 통해 mysql로 접근이 가능하다.

express sequelize 세팅

npm install sequelize mysql2 sequelize-cli

npx sequelize-cli init <- 시퀄라이즈 초기 설정

config 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"development": {
"username": "test",
"password": "1210ss",
"database": "test",
"host": "mysql",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}

데이터 베이스를 환경에 맞게 연결할 수 있는 옵션이 있다. 간단하게 dev 환경 세팅만 진행 후 연결을 해보도록 한다.

1
2
3
4
5
6
7
8
9
10
11
12
// app.js
// ...

sequelize.sync({ force: false }) // force: false 실행시마다 테이블을 새로 재생성할건가에 대한 옵션 true or false
.then(() => {
console.log('데이터베이스 연결 성공!');
})
.catch((err) => {
console.log(err);
});

// ...

다시 docker의 express를 실행해주면 데이터 베이스 연결이 완료된다.

1
2
3
4
5
6
7
8
9
10
11
 ✘ hanjuryeon  ~/docker-test   main ±  docker-compose up docker-test
Starting docker-node-app ... done
Attaching to docker-node-app
docker-node-app | [nodemon] 2.0.15
docker-node-app | [nodemon] to restart at any time, enter `rs`
docker-node-app | [nodemon] watching path(s): *.*
docker-node-app | [nodemon] watching extensions: js,mjs,json
docker-node-app | [nodemon] starting `node app.js`
docker-node-app | express app start
docker-node-app | Executing (default): SELECT 1+1 AS result
docker-node-app | 데이터베이스 연결 성공!
Author

han Ju Ryeon

Posted on

2021-12-30

Updated on

2021-12-30

Licensed under

댓글