LoginSignup
0
2

More than 3 years have passed since last update.

MariaDB のコンテナ起動時に init.sql を流す

Last updated at Posted at 2019-07-26

MariaDBのコンテナ起動時に、ユーザー追加やデータベース作成などを済ませておきたかった。

以下、dockerhubより。

Initializing a fresh instance

When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mariadb services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

どうやらホストマシンのディレクトリに実行したいSQLファイルを入れていおいて /docker-entrypoint-initdb.d というディレクトリにマウントするとできるらしい。

setup ディレクトリに init.sql を配置

適当なディレクトリに init.sql を入れておく。

$ cat ./setup/init.sql
CREATE USER me IDENTIFIED BY 't_horikoshi';
CREATE DATABASE `mydb`;
GRANT ALL PRIVILEGES ON `mydb`.* TO me IDENTIFIED BY 'me';

コンテナ起動

-vオプションに init.sql を含んだディレクトリを /docker-entrypoint-initdb.d にマウントするように指定する。

$ docker run -itd --name mymariadb  \
   -p 3306:3306 \
   -e MYSQL_ROOT_PASSWORD=root \
   -v="$PWD/setup":/docker-entrypoint-initdb.d \
   mariadb:latest

結果確認

コマンドラインを立ち上げる。

$ docker exec -it mymariadb mysql -uroot -p -h 127.0.0.1

クエリを打って確認。

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mysql              |
| performance_schema |
+--------------------+

mydbが作成されていることが無事確認できました。
ちなみにMySQLも同じらしい。

0
2
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
0
2