docker compose make sure postgres is ready before starting other service

Sometimes we want to start a service in docker compose after some dependency is ready. In this case, we want to wait for PostgreSQL.

The key here is healthcheck on the PostgreSQL

healthcheck:
  test: [ "CMD-SHELL", "pg_isready -U postgres" ]
  interval: 10s
  timeout: 5s
  retries: 5

and depends_on on the service

depends_on:
  postgres:
    condition: service_healthy

Full docker-compose.yaml

version: '3.8'
services:
  postgres:
    image: postgres:11.6-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: 12345
      POSTGRES_DB: todo
    ports:
      - 5432:5432
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U postgres" ]
      interval: 10s
      timeout: 5s
      retries: 5

  backend:
    build: backend
    environment:
      DB_HOST: postgres
    ports:
      - 5000:5000
    depends_on:
      postgres:
        condition: service_healthy

volumes:
  postgres_volume:

Last updated