> For the complete documentation index, see [llms.txt](https://til.yulrizka.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://til.yulrizka.com/docker/docker-compose-make-sure-postgres-is-ready-before-starting-other-service.md).

# 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

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

and `depends_on` on the service

```yaml
depends_on:
  postgres:
    condition: service_healthy
```

Full docker-compose.yaml

```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:
```
