乐闻世界logo
搜索文章和话题

Prometheus 支持哪些服务发现机制,如何配置?

2月21日 15:37

Prometheus 服务发现机制详解:

静态配置

yaml
scrape_configs: - job_name: 'node' static_configs: - targets: ['192.168.1.10:9100', '192.168.1.11:9100'] labels: datacenter: 'dc1'

Kubernetes 服务发现

yaml
scrape_configs: - job_name: 'kubernetes-pods' kubernetes_sd_configs: - role: pod relabel_configs: - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] action: keep regex: true - source_labels: [__meta_kubernetes_pod_ip] target_label: __address__ replacement: $1:9104

Kubernetes 角色类型

  • pod:发现所有 Pod
  • service:发现所有 Service
  • endpoints:发现 Service 的 Endpoints
  • endpointslices:发现 EndpointSlices
  • node:发现所有 Node
  • ingress:发现所有 Ingress

Consul 服务发现

yaml
scrape_configs: - job_name: 'consul' consul_sd_configs: - server: 'consul.example.com:8500' services: ['web', 'api'] tag_separator: ',' scheme: http

DNS SRV 服务发现

yaml
scrape_configs: - job_name: 'dns' dns_sd_configs: - names: ['_prometheus._tcp.example.com'] type: SRV port: 9100

EC2 服务发现

yaml
scrape_configs: - job_name: 'ec2' ec2_sd_configs: - region: us-east-1 access_key: AKIA... secret_key: xxx...

Relabel Configs(重标签配置)

  • replace:替换标签值
  • keep:保留匹配的目标
  • drop:丢弃匹配的目标
  • keep_if_equal:如果标签相等则保留
  • drop_if_equal:如果标签相等则丢弃
  • hashmod:哈希取模
  • labelmap:标签映射

常用元标签

  • __meta_kubernetes_pod_name:Pod 名称
  • __meta_kubernetes_service_name:Service 名称
  • __meta_consul_service_metadata_*:Consul 元数据
  • __meta_ec2_tag_*:EC2 标签

最佳实践

  1. 使用注解控制 Pod 是否被采集
  2. 合理使用标签进行分组
  3. 定期清理无用的服务发现配置
  4. 使用 relabel_configs 过滤不需要的目标
  5. 监控服务发现的性能影响
标签:Prometheus