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も同じらしい。