
前回、以下の記事でPostgreSQLをDokcerで立てて開発する方法を紹介した。
今回は、dockerを立ち上げた際に自動的にcreate tableを流す方法について説明する。
まず前回同様 docker-compose.yml を用意する。
postgresql:
image: postgres:10.5
container_name: postgresql
ports:
- 5432:5432
volumes:
- ./postgres/init:/docker-entrypoint-initdb.d
environment:
POSTGRES_USER: root
POSTGRES_PASSWORD: root
POSTGRES_DB: lgtmoon
POSTGRES_INITDB_ARGS: "--encoding=UTF-8"
hostname: postgres
restart: always
user: root
ここで重要なのがこの部分である。
volumes:
- ./postgres/init:/docker-entrypoint-initdb.d
これは、ローカル環境の ./postgres/init をdockerの /docker-entrypoint-initdb.d にマウントするということである。そして、 /docker-entrypoint-initdb.d 以下にシェルスクリプトやsqlをおいておくと、docker起動時に自動的に実行してくれる。つまり、./postgres/init ディレクトリを作成し、そこにsqlやシェルスクリプトをおいておくことで、docker起動時にテーブルが作成されるというわけだ。
今回は、 ./postgres/init/1_create.sql というファイルを作成した。
create table if not exists image (
id bigserial primary key,
content_type varchar(32) not null,
created_at timestamp not null default current_timestamp,
status smallint not null,
bin bytea default null
);
create index image_created_at on image (created_at);
重要なのは、1_ 2_ のような数字で始まっていることである。dockerはこの数字を見て 1 から順に実行していく。
もう一つ重要なのが、 docker-compose.yml に POSTGRES_DB: lgtmoon を追記したことである。一つのホストで複数のdatabaseを使う場合はこの書き方は使えないが、DBが一つの場合はこの書き方をしておくといろいろと考えることが減って楽である。
- 作者:曽根 壮大
- 発売日: 2019/03/06
- メディア: 単行本(ソフトカバー)
- 作者:Bill Karwin
- 発売日: 2013/01/26
- メディア: 大型本