1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DockerのMySQLコンテナへ初期データを投入する

Last updated at Posted at 2022-11-09

前提

自動テスト用のデータベースサーバを作りたいけど、テーブル定義が変更される度にコンテナ内でdumpファイルを実行するのが面倒臭い!
コンテナを立ち上げる度にdumpファイルをセットしてくれないかのう、、

という課題にぶち当たった際に、以下の機能を知ったので忘備録的に残しておきます。

Initializing a fresh instance
https://hub.docker.com/_/mysql

最終的なディレクトリ構成

docker
├── docker-compose.yml
├── .env
└── initdb.d
    └── test_dump.sql

初期データを入れる方法

docker-compose.ymlの作成

initdb.d/に置いたdumpファイルを、docker-entrypoint-initdb.d/にマウントしてくれる

docker-compose.yml
version: "3"
services:
  mysql:
    image: mysql:8.0
    container_name: test
    volumes:
      # initdb.d配下にある.sh, .sql and .sql.gz拡張子をアルファベット順に実行出来る
      - ./initdb.d:/docker-entrypoint-initdb.d
    environment:
      - MYSQL_DATABASE=${DB_NAME}
      - MYSQL_USER=${DB_USER}
      - MYSQL_PASSWORD=${DB_PASS}
      - MYSQL_ROOT_PASSWORD=${DB_PASS}
      - TZ=${TZ}
    ports:
      - 3306:3306
.env
DB_NAME=test_database
DB_USER=test
DB_PASS=test_password
TZ=Asia/Tokyo

dumpファイルをinitdb.d/に配置する

[cyber_diver@server initdb.d]$ ls
test_dump.sql

コンテナを立ち上げる

[cyber_diver@server docker]$ docker-compose up -d

コンテナに入ってマウントされたファイルを確認する

test_dump.sqlが生成されていることを確認

[cyber_diver@server docker]$ docker exec -it test bash
bash-4.4# cd docker-entrypoint-initdb.d/                               
bash-4.4# ls
test_dump.sql

テーブルが作られていることを確認

やったぜ

bash-4.4# mysql -uroot -p test_database
Enter password: 
...

mysql> show tables;
+------------------------------------------------------------+
| Tables_in_test_database                                    |
+------------------------------------------------------------+
| test_table                                                 |
+------------------------------------------------------------+
1 rows in set (0.04 sec)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?