LoginSignup
9
9

More than 3 years have passed since last update.

docker-composeでPostgreSQL/MySQL起動時に初期データを敷きこむ

Last updated at Posted at 2019-08-06

概要

dockerで立ち上げたPostgreSQLやMySQLに初期データを敷きこんでおきたいことはよくあるはず。
身の回りで意外と知らない人が多かったので記事として残しておきます。

DockerでDB起動時にデータを敷きこむ

PostgreSQLの場合

docker-compose.yml内のdb:/docker-entrypoint-initdb.dがポイントです。

ここではローカルのdbディレクトリの中に初期化したいファイルを置いておきます。
対応しているファイルは以下です。

  • *.sql
  • *.sql.gz
  • *.sh
docker-compose.yml
version: '3.1'

services: 
  pg:
    image: postgres:latest
    ports: 
      - "15432:5432"
    environment: 
      POSTGRES_PASSWORD: example1
      POSTGRES_USER: example1
      POSTGRES_DB: mydb1
    volumes:
      - ./db:/docker-entrypoint-initdb.d

(参考)MySQLの場合

dockerdb:/docker-entrypoint-initdb.dを定義して

ここではローカルのdbディレクトリの中に初期化したいファイルを置いておきます。

対応しているファイルはPostgreSQLと同様に、以下です。

  • *.sql
  • *.sql.gz
  • *.sh
docker-compose.yml
version: '3.1'

services: 
  mysql:
    image: mysql:8.0.17
    ports: 
      - "13306:3306"
    environment: 
      MYSQL_ROOT_PASSWORD: example2
      MYSQL_USER: example2
      MYSQL_DATABASE: mydb2
    volumes:
      - ./db:/docker-entrypoint-initdb.d

参考ここまで。
以降はPostgreSQLを使った手順になっています。

さて、./dbディレクトリにsqlファイルを作成します。
このsqlファイルに初期化して敷き込みたいデータを書いておきます。

db/init.sql

db/init.sql
set client_encoding = 'UTF8';

create table users (
  id serial primary key,
  name varchar not null,
  age integer not null
);

insert into users(name, age) values 
  ('ichigo.chocomint', 99),
  ('banana.chocomint', 98),
  ('pinapple.chocomint', 97)
;

docker-composeを起動します。

docker-compse up

データが入っているか確認する

なんでもよいのですが、TypeScriptで書いてみました。

index.ts
import { Client } from 'pg';

type DatabaseSetting = {
  host: string;
  port: number;
  user: string;
  password: string;
  database: string;
};

class Postgres {
  static async getClient(setting: DatabaseSetting) {
    const { host, port, user, password, database } = setting;
    const client = new Client({
      host,
      port,
      user,
      password,
      database
    });
    await client.connect();
    return client;
  }
}

async function pgSampleQuery(client: Client) {
  return client.query('select * from users');
}

async function main() {
  const pgClient = await Postgres.getClient({
    host: 'localhost',
    port: 15432,
    user: 'example1',
    password: 'example1',
    database: 'mydb1'
  });

  const result = await pgSampleQuery(pgClient);
  console.log(result.rows);
}

// execute
main();

結果が以下の通りになっているのでOKでした。

[ { id: 1, name: 'ichigo.chocomint', age: 99 },
  { id: 2, name: 'banana.chocomint', age: 98 },
  { id: 3, name: 'pinapple.chocomint', age: 97 } ]

おわり。

9
9
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
9
9