【Docker】MariaDBのコンテナに初期データを投入する

Dockerを立ち上げた際、同時に初期データを投入する方法です。

初期データの投入方法

今回は、公式のMariaDBコンテナを使います。
Docker SecretsのInitializing a fresh instanceの項に、次のように記載されています。

https://hub.docker.com/_/mariadb/

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.

ドキュメントによると、/docker-entrypoint-initdb.dの直下に次の拡張子ファイルを置くと立ち上げ時にインポートします。

  • sh
  • sql
  • sql.gz

また、インポートするデータベースはenvironmentに指定したMYSQL_DATABASEです。

SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

設定方法

ディレクトリ構成

今回は、初期データをinit.sqlというファイル名にしています。

/
├──docker-compose.yml
└──stacks/
    └── db
       ├── Dockerfile
       └── docker-entrypoint-initdb.d
           └── init.sql

docke-compose.yml

インポートするデータベースを指定する必要があるため、MYSQL_DATABASEを指定します。

version: "3.2"
services:
  db:
    build:
      context: ./stacks/db/
    environment:
      MYSQL_HOST: <host名>
      MYSQL_DATABASE: <データベース名>
      MYSQL_ROOT_PASSWORD: <rootユーザのパスワード>

Dockerfile

コンテナのバージョンは、10.xを指定します。

FROM mariadb:10.4

COPY ./docker-entrypoint-initdb.d/ ./docker-entrypoint-initdb.d/

該当ディレクトリに対象ファイルをCOPYします。



以上です。
これで、docker-compose upで立ち上げた時にインポートが実行されます。

©︎2017-2018 WebSandBag