services:
  # 1. PostgreSQL 数据库
  postgres-server:
    image: postgres:17-alpine
    container_name: postgres-server
    restart: unless-stopped
    volumes:
      # 持久化数据
      - /etc/localtime:/etc/localtime:ro
      - ./zbx_env/var/lib/postgresql/data:/var/lib/postgresql/data:rw
      # 【新增】持久化配置文件，调优 postgresql.conf 就在这个目录下
      - ./zbx_env/etc/postgresql:/etc/postgresql:rw
    environment:
      POSTGRES_USER: zabbix
      POSTGRES_PASSWORD: zabbix
      POSTGRES_DB: zabbix
    # 使用自定义配置文件启动的命令（确保读取挂载的配置）
    command: ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]
    networks:
      - zabbix-net

  # 2. Zabbix Server
  zabbix-server-pgsql:
    image: ghcr.io/solyhe/zabbix-server-pgsql-python:latest
    container_name: zabbix-server-pgsql
    restart: unless-stopped
    depends_on:
      - postgres-server
    volumes:
      # 【核心】持久化整个配置目录，调优 zabbix_server.conf 就在这里
      - /etc/localtime:/etc/localtime:ro
      - ./zbx_env/etc/zabbix:/etc/zabbix:rw
      - ./zbx_env/usr/lib/zabbix/externalscripts:/usr/lib/zabbix/externalscripts:rw
      - ./zbx_env/usr/lib/zabbix/alertscripts:/usr/lib/zabbix/alertscripts:rw
    environment:
      DB_SERVER_HOST: postgres-server
      POSTGRES_USER: zabbix
      POSTGRES_PASSWORD: zabbix
      POSTGRES_DB: zabbix
    ports:
      - "10051:10051"
    networks:
      - zabbix-net

  # 3. Zabbix Web
  zabbix-web-nginx-pgsql:
    image: zabbix/zabbix-web-nginx-pgsql
    container_name: zabbix-web-nginx-pgsql
    restart: unless-stopped
    depends_on:
      - zabbix-server-pgsql
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - ./zbx_env/etc/zabbix/web/zabbix.conf.php:/etc/zabbix/web/zabbix.conf.php:rw
    ports:
      - "80:8080"
    environment:
      ZBX_SERVER_HOST: zabbix-server-pgsql
      DB_SERVER_HOST: postgres-server
      POSTGRES_USER: zabbix
      POSTGRES_PASSWORD: zabbix
      POSTGRES_DB: zabbix
      PHP_TZ: Asia/Shanghai
    networks:
      - zabbix-net

  # 4. Zabbix Agent
  zabbix-agent:
    image: zabbix/zabbix-agent
    container_name: zabbix-agent
    restart: unless-stopped
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /:/host:ro
      - /var/run:/var/run:rw
    environment:
      - ZBX_HOSTNAME=Zabbix-Server
      - ZBX_SERVER_HOST=zabbix-server-pgsql
    networks:
      - zabbix-net
      
  grafana:
    image: grafana/grafana:latest
    container_name: grafana
    hostname: grafana
    ports:
      - 3000:3000
    environment:
      - "GF_INSTALL_PLUGINS=alexanderzobnin-zabbix-app"
    depends_on:
      - zabbix-web-nginx-pgsql
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
      - ./grafana:/var/lib/grafana:rw
    user: root
    networks:
      - zabbix-net
    stop_grace_period: 5s
    restart: always
  

networks:
  zabbix-net:
    name: zabbix-net
    driver: bridge
    ipam:
      config:
        - subnet: 172.31.100.0/24
