version: '3.8'
services:
  postgres:
    image: postgres:16-alpine
    container_name: postgres-main
    restart: unless-stopped
    networks:
    - database-internal
    env_file:
    - .env
    environment:
      POSTGRES_USER: ${POSTGRES_ADMIN_USER}
      POSTGRES_PASSWORD: ${POSTGRES_ADMIN_PASSWORD}
      POSTGRES_DB: postgres
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
    - /mnt/psql-data:/var/lib/postgresql/data
    - ./init-scripts:/docker-entrypoint-initdb.d:ro
    - ./backups:/backups
    ports:
    - 127.0.0.1:5432:5432
    command:
    - postgres
    - -c
    - max_connections=200
    - -c
    - shared_buffers=2GB
    - -c
    - effective_cache_size=6GB
    healthcheck:
      test:
      - CMD-SHELL
      - pg_isready -U ${POSTGRES_ADMIN_USER} -d postgres
      interval: 10s
      timeout: 5s
      retries: 5
  pgadmin:
    image: dpage/pgadmin4:9.9
    container_name: pgadmin
    restart: unless-stopped
    networks:
    - database-internal
    - traefik-public
    env_file:
    - .env
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_PASSWORD}
      PGADMIN_CONFIG_SERVER_MODE: 'True'
      PGADMIN_CONFIG_MASTER_PASSWORD_REQUIRED: 'False'
      PGADMIN_SERVER_JSON_FILE: /pgadmin4/servers.json
      PGADMIN_CONFIG_AUTHENTICATION_SOURCES: '[''webserver'']'
      PGADMIN_CONFIG_WEBSERVER_REMOTE_USER: '''X-authentik-username'''
      PGADMIN_CONFIG_WEBSERVER_AUTO_CREATE_USER: 'True'
    volumes:
    - pgadmin-data:/var/lib/pgadmin
    - ./pgadmin-config/servers.json:/pgadmin4/servers.json:ro
    labels:
    - traefik.enable=true
    - traefik.http.routers.pgadmin.rule=Host(`pgadmin.ai-impress.com`)
    - traefik.http.routers.pgadmin.entrypoints=websecure
    - traefik.http.routers.pgadmin.tls.certresolver=cloudflare
    - traefik.http.services.pgadmin.loadbalancer.server.port=80
    - traefik.http.routers.pgadmin.middlewares=authentik@file
    depends_on:
      postgres:
        condition: service_healthy
volumes:
  pgadmin-data: null
networks:
  database-internal:
    external: true
  traefik-public:
    external: true
