version: '3'

services:
  op-proxy:
    image: caddy:2-alpine
    restart: always
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - op-proxy-data:/data
      - op-proxy-config:/config
      - ./caddy/Caddyfile:/etc/caddy/Caddyfile
    depends_on:
      - op-dashboard
      - op-api

  op-db:
    image: postgres:14-alpine
    restart: always
    volumes:
      - op-db-data:/var/lib/postgresql/data
    healthcheck:
      test: [ 'CMD-SHELL', 'pg_isready -U postgres' ]
      interval: 10s
      timeout: 5s
      retries: 5
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    # Uncomment to expose ports
    # ports:
    #   - 5432:5432

  op-kv:
    image: redis:7.2.5-alpine
    restart: always
    volumes:
      - op-kv-data:/data
    command: [ 'redis-server', '--maxmemory-policy', 'noeviction' ]
    # Uncomment to expose ports
    # ports:
    #   - 6379:6379

  op-geo:
    image: observabilitystack/geoip-api:latest
    restart: always

  op-ch:
    image: clickhouse/clickhouse-server:24.3.2-alpine
    restart: always
    volumes:
      - op-ch-data:/var/lib/clickhouse
      - op-ch-logs:/var/log/clickhouse-server
      - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/op-config.xml:ro
      - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/op-user-config.xml:ro
      - ./clickhouse/init-db.sh:/docker-entrypoint-initdb.d/init-db.sh:ro
    healthcheck:
      test: [ 'CMD-SHELL', 'clickhouse-client --query "SELECT 1"' ]
      interval: 10s
      timeout: 5s
      retries: 5
    ulimits:
      nofile:
        soft: 262144
        hard: 262144

  op-api:
    image: lindesvard/openpanel-api:latest
    restart: always
    command: >
      sh -c "
        echo 'Waiting for PostgreSQL to be ready...'
        while ! nc -z op-db 5432; do
          sleep 1
        done
        echo 'PostgreSQL is ready'

        echo 'Waiting for ClickHouse to be ready...'
        while ! nc -z op-ch 8123; do
          sleep 1
        done
        echo 'ClickHouse is ready'

        echo 'Running migrations...'
        CI=true pnpm -r run migrate:deploy

        pnpm start
      "
    depends_on:
      - op-db
      - op-ch
      - op-kv
      - op-geo
    env_file:
      - .env

  op-dashboard:
    image: lindesvard/openpanel-dashboard:latest
    restart: always
    depends_on:
      - op-api
    env_file:
      - .env

  op-worker:
    image: lindesvard/openpanel-worker:latest
    restart: always
    depends_on:
      - op-api
    env_file:
      - .env
    deploy:
      mode: replicated
      replicas: $OP_WORKER_REPLICAS

volumes:
  op-db-data:
    driver: local
  op-kv-data:
    driver: local
  op-ch-data:
    driver: local
  op-ch-logs:
    driver: local
  op-proxy-data:
    driver: local
  op-proxy-config:
    driver: local
