iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐳

Health Check Method for PostgreSQL in Docker Compose

に公開

This is a repurposed article based on a scrap written on 2023/01/31 (based on information from that time).

When using Docker Compose with a PostgreSQL database container, don't you find that it takes a long time for the APP container to be ready to connect because of various initialization steps on the first startup? (I did.)

If the initialization of the APP container depends on the database connection, don't you find that it fails halfway and results in an inconsistent state? (I did.)

Since the APP was Django, I prepared the following Python script and inserted a mechanism in the APP container's startup script to wait for the database to be ready.

wait-for-db-up.py
""" Wait until database server is up """
import os
import sys
import time
import urllib.parse
import psycopg2

database_url = os.getenv('DATABASE_URL')

if not database_url:
    sys.exit(1)

parsed_params = urllib.parse.urlparse(database_url)
username = parsed_params.username
password = parsed_params.password
database = parsed_params.path[1:]
hostname = parsed_params.hostname

retry_count = 0
while retry_count < 300:
    try:
        connection = psycopg2.connect(host=hostname, database=database,
                                      user=username, password=password)
        connection.get_backend_pid()
        connection.close()
        sys.exit(0)
    except psycopg2.OperationalError as e:
        retry_count += 1
        print(e)
    time.sleep(1)
    print('Retry ...')

print('Over retry limit')
sys.exit(1)

Even so, it sometimes didn't work well, and I was wondering what to do. Then I found a simpler method.

By adding the following settings to the DB container:

docker-compose.yaml
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres || exit 1"]
      interval: 10s
      timeout: 5s
      retries: 10

I learned that you just need to add the following settings to the dependent APP container:

docker-compose.yaml
    depends_on:
      db:
        condition: service_healthy

Reference

https://gotohayato.com/content/562/

Discussion