docker-compose.yml
version: '3.1'
services:
db:
image: postgres
restart: always
ports:
- 5432:5432
volumes:
- ./postgres/init:/docker-entrypoint-initdb.d #初回起動時用
- ./postgres/data:/var/lib/postgresql/data #永続化用
environment:
POSTGRES_PASSWORD: #パスワード
POSTGRES_DB: #DB名
volumes
でマウントする。
:
の左側がローカルマシン内のディレクトリ、右側がDockerコンテナ上でのディレクトリ。
初回起動時スクリプト./postgres/init:/docker-entrypoint-initdb.d
Dockerコンテナ上のpostgresqlの起動時にdataディレクトリ(/var/lib/postgresql/data
)が空だった場合、/docker-entrypoint-initdb.d
配下のファイル(*.sql, *.shなど)が実行される。
参考:https://hub.docker.com/_/postgres
If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.
Warning: scripts in /docker-entrypoint-initdb.d are only run if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup. One common problem is that if one of your /docker-entrypoint-initdb.d scripts fails (which will cause the entrypoint script to exit) and your orchestrator restarts the container with the already initialized data directory, it will not continue on with your scripts.
永続化./postgres/data:/var/lib/postgresql/data
Dockerコンテナ上の/var/lib/postgresql/data
をローカルマシンでマウントしておくことで、万一コンテナ上のDBが吹き飛んでもローカルに生き残るので復旧できる。