version: '3.9'

services:
  pgbouncer:
    image: pgbouncer/pgbouncer:1.21.0
    environment:
      - DATABASES_HOST=postgresql_primary
      - DATABASES_PORT=5432
      - DATABASES_USER=postgres
      - DATABASES_PASSWORD_FILE=/run/secrets/pg_root_password
      - DATABASES_DBNAME=*
      - POOL_MODE=transaction
      - MAX_CLIENT_CONN=100
      - DEFAULT_POOL_SIZE=20
      - MIN_POOL_SIZE=5
      - RESERVE_POOL_SIZE=3
      - SERVER_LIFETIME=3600
      - SERVER_IDLE_TIMEOUT=600
      - LOG_CONNECTIONS=1
      - LOG_DISCONNECTIONS=1
    secrets:
      - pg_root_password
    networks:
      - database-network
    healthcheck:
      test: ["CMD", "psql", "-h", "localhost", "-p", "6432", "-U", "postgres", "-c", "SELECT 1;"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 30s
    deploy:
      resources:
        limits:
          memory: 512M
          cpus: '0.5'
        reservations:
          memory: 128M
          cpus: '0.1'
      placement:
        constraints:
          - "node.labels.role==db"
      labels:
        - traefik.enable=false

secrets:
  pg_root_password:
    external: true

networks:
  database-network:
    external: true