3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

docker-composeで起動したpostgresqlの初回起動時スクリプト実行とDB永続化の方法

Last updated at Posted at 2022-10-05

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が吹き飛んでもローカルに生き残るので復旧できる。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?