ing486sarang avatar

Customize your MySQL database in Docker

ing486sarang

Published: 28 Aug 2018 › Updated: 28 Aug 2018Customize your MySQL database in Docker

Customize your MySQL database in Docker

table과 data 를 포함하고 있는 custom MySQL Server 를 docker 로 만들어본다.

1. Create SQL Scripts

스크린샷 2018-08-28 오후 12.09.16.png

working directory를 만들고 table과 data를 포함하고 있는 .sql scripts를 만들자.

스크린샷 2018-08-28 오후 12.10.37.png

CreateTable.sql 파일을 생성한다.

스크린샷 2018-08-28 오후 12.10.44.png

InsertData.sql 파일을 생성한다.

2. Create a Docker image for your customized MySQL Database

스크린샷 2018-08-28 오후 12.12.49.png

Dockerfile 의 내용은 아래와 같다.

# Derived from official mysql image (our base image)
FROM mysql
# Add a database
ENV MYSQL_DATABASE company
# Add the content of the sql-scripts/ directory to your image
# All scripts in docker-entrypoint-initdb.d/ are automatically
# executed during container startup
COPY ./sql-scripts/ /docker-entrypoint-initdb.d/


Docker image 를 생성한다.

$ cd ~/my-mysql/
$ docker  build -t my-mysql .
Sending build context to Docker daemon  4.608kB
Step 1/2 : FROM mysql
latest: Pulling from library/mysql
Digest: sha256:691c55aabb3c4e3b89b953dd2f022f7ea845e5443954767d321d5f5fa394e28c
Status: Downloaded newer image for mysql:latest
 ---> 5195076672a7
Step 2/2 : ADD sql-scripts/ /docker-entrypoint-initdb.d/
 ---> 25065c3d93c0
Successfully built 25065c3d93c0
Successfully tagged my-mysql:latest


image가 잘 생성되었는지 확인하자. docker images 라는 명령어로 확인해보면 아래와 같이 image가 잘 생성되었음을 확인할 수 있다.

$ docker images
REPOSITORY                                                   TAG                 IMAGE ID            CREATED             SIZE
my-mysql                                                     latest              0f9b9fe27415        4 seconds ago       484MB


MySQL container 를 image로부터 start 한다. 기본 포트인 3306 포트로 host 포트와 연결되고 my-mysql image로부터 my-mysql 이라는 이름으로 container가 구동된다. docker stop 할 경우 container까지 remove하고 싶은 경우에는 --rm 옵션을 사용한다.

$ docker run -d --rm -p 3306:3306 --name my-mysql \
-e MYSQL_ROOT_PASSWORD=supersecret my-mysql


docker exec 를 통하여 MySQL container가 잘 실행되었는지 검증한다. docker exec를 통하여 container 에 접속할 수 있다. mysql client에서 select version(); 을 통하여 server 의 버전을 확인할 수 있다. 가장 최근 버전의 MySQL server가 설치되었다.

$ docker exec -it my-mysql bash
root@c86ff80d7524:/# mysql -uroot -p
Enter password: (supersecret)
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.12    |
+-----------+
1 row in set (0.00 sec)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| company            |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
mysql> use company;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+-------------------+
| Tables_in_company |
+-------------------+
| employees         |
+-------------------+
1 row in set (0.00 sec)
mysql> show columns from employees;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| first_name | varchar(25) | YES  |     | NULL    |       |
| last_name  | varchar(25) | YES  |     | NULL    |       |
| department | varchar(15) | YES  |     | NULL    |       |
| email      | varchar(50) | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
mysql> select * from employees;
+------------+-----------+------------+-------------------+
| first_name | last_name | department | email             |
+------------+-----------+------------+-------------------+
| Lorenz     | Vanthillo | IT         | lvthillo@mail.com |
+------------+-----------+------------+-------------------+
1 row in set (0.01 sec)

3. MySQL Workbench 를 이용한 connection test

container 외부에서 MySQL client인 MySQL Workbench를 통하여 connection test를 해 보자.
Mac OS에 이미 설치되어 있었던 MySQL Workbench 6.x 에서 최신 MySQL Server connection 시 위의 그림과 같은 에러가 난다. MySQL Workbench 버전 문제인지 몰라서 하루 정도 삽질을 했다. 이런 경우 최신의 MySQL Workbench를 설치하면 문제가 간단하게 해결된다.

스크린샷 2018-08-27 오후 6.39.01.png

최신의 MySQL Workbench 에서 접속이 잘 된다.

스크린샷 2018-08-28 오후 12.20.39.png

4. MySQL 데이타 유지를 위해서

docker run 시 --rm 옵션으로 MySQL container를 시작하면 docker stop 할 경우 container가 지워지면서 자연스럽게 데이타베이스도 사라지게 된다. (--rm 옵션을 사용하지 않은 경우에는 docker stop 할 경우 container가 지워지지 않기 때문에 docker restart 를 하게 되면 데이타베이스는 그대로 유지가 된다. 하지만 docker rm 시 데이타베이스가 지워지는 것은 어쩔 수 없다.)
운영모드에서 MySQL container의 데이타베이스를 그대로 유지하고 싶을 경우에는 --volume 옵션을 사용하면 해결할 수 있습니다. --volume 옵션(또는 -v 옵션) 은 데이터베이스 데이터가 저장되는 container 내부의 경로인 /var/lib/mysql 를 로컬 컴퓨터의 경로로(예를 들어 $(pwd)/docker/data)로 연결하면, 컨테이너 삭제와 상관 없이 데이터를 유지할 수 있습니다.

docker run -d --rm -p 3306:3306 --name my-mysql \
-e MYSQL_ROOT_PASSWORD=supersecret \
-v /Users/naver/Documents/IntelliJ/StudyWorkSpace/springboot_guides/my-mysql/data:/var/lib/mysql \
my-mysql


my-mysql/data 경로에 database 파일이 저장되게 됩니다. 이제는 container 가 제거되어도 데이타베이스는 그대로 유지됩니다.

스크린샷 2018-08-29 오후 2.15.33.png

5. Use bind mounts to customize your MySQL database in Docker

$ docker run -d -p 3306:3306 --name my-mysql \
-v ~/my-mysql/sql-scripts:/docker-entrypoint-initdb.d/ \
-e MYSQL_ROOT_PASSWORD=supersecret \
-e MYSQL_DATABASE=company \
mysql

6. 참고

Leave Customize your MySQL database in Docker to:

Written by

Read more #mysql posts


Best Posts From ing486sarang

We have not curated any of ing486sarang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ing486sarang