1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

docker postgresql のhealth checkの備忘録

Posted at

TL;DR

  1. dockerのpostresql containerにhealthcheck blockを追加
  2. test block内に pg_isready commandを利用したhealth check コマンドを追加する
  3. application container 側のdepends_on blockに db: condition: service_healthyを追加

0. 参考

docker blog
postgre docker image
docker compose reference
peter-evans/docker-compose-healthcheck #17

1. postgresql imageの準備をする

tree ${PROJECT_PATH} -L 2
${PROJECT_PATH}
├── README.md
├── compose.yaml
├── database
│   └── dockerfile
${PROJECT_PATH}/compose.yaml
services:
  database_container:
    container_name: database_container
    build:
      context: ./database
      dockerfile: dockerfile
    tty: true
    restart: always
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_USER: example

volumes:
  pgdata: {}
FROM postgres:16

2. healthcheck blockを追加する

docker blogを参考に、health check blockの追加を実施。

${PROJECT_PATH}/compose.yaml
services:
  database_container:
      container_name: database_container
      # ...
      # 追記
      healthcheck:
      test: ["CMD-SHELL", "pg_isready"]
      interval: 1s
      timeout: 5s
      retries: 10
% docker compose up --build
database_container  | 2024-08-25 08:17:56.724 UTC [40] FATAL:  role "root" does not exist

role "root" does not existとなってしまい、まぁ起動しているから追加すれば良いのですが、毎回でるの辛いので、pg_isreadyから確認する。

3. health check blockを修正する

-U username
--username=username
Connect to the database as the user username instead of the default.
https://www.postgresql.org/docs/current/app-pg-isready.html

peter-evans/docker-compose-healthcheck issues 17
peter-evans/docker-compose-healthcheck issues 17

上記から、container > healthcheck > testコマンドないでuserを設定して渡らせる。

${PROJECT_PATH}/compose.yaml
services:
  database_container:
    container_name: database_container
    build:
      context: ./database
      dockerfile: dockerfile
    tty: true
    restart: always
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_USER: example
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
      interval: 1s
      timeout: 5s
      retries: 10
docker compose up --build
database_container  | 2024-08-25 08:19:17.311 UTC [1] LOG:  database system is ready to accept connections
database_container  | 2024-08-25 08:24:17.340 UTC [27] LOG:  checkpoint starting: time
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?