一、背景简介

随着业务向云原生架构迁移,原有的监控系统需要升级以适应容器化环境。本系列文章介绍如何使用 Kube-Prometheus 监控 K8s 集群外部的主机和中间件服务。

核心特点:

  • 支持监控 K8s 集群外部的服务(MySQL、Redis、RocketMQ 等)
  • 通过环境标签(platform)区分不同环境的监控数据
  • 基于 Prometheus Operator 的 ServiceMonitor 机制实现服务发现

二、技术原理

2.1 K8s 访问外部服务

K8s 集群内的 Pod 访问外部服务的原理:

关键步骤:

  1. 创建 Endpoints 资源,指向外部服务的 IP 地址
  2. 创建 Service 资源,不配置 selector,关联到手动创建的 Endpoints
  3. Pod 通过 Service 名称访问外部服务

2.2 ServiceMonitor 原理

Prometheus Operator 通过 ServiceMonitor 实现服务发现:

工作流程:

  1. ServiceMonitor 通过 selector 选择目标 Service
  2. Prometheus Operator 监听 ServiceMonitor 变化,更新 Prometheus 配置
  3. Prometheus 根据配置发现 Endpoints,采集指标数据

三、环境准备

3.1 创建命名空间

kubectl create namespace monitoring
# 执行结果:namespace/monitoring created

配置角色和权限

monitoring-role.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: prometheus-k8s
  namespace: mos-monitoring
rules:
  - apiGroups: [""]
    resources: 
      - services
      - endpoints
      - pods
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - extensions
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch

monitoring-role-binding.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: prometheus-k8s
  namespace: mos-monitoring
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: prometheus-k8s
subjects:
  - kind: ServiceAccount
    name: prometheus-k8s
    namespace: monitoring

配置说明:

  • Role 定义了 Prometheus 在业务命名空间中的访问权限
  • RoleBinding 将 Role 绑定到 Prometheus 的 ServiceAccount

四、监控实施

环境隔离方案:
为了区分不同环境的监控数据,在 Service 中添加自定义标签 platform: <env>,通过 ServiceMonitor 的 targetLabels 配置将该标签添加到指标中。

后续章节内容:

五、注意事项

  1. 网络连通性:确保 K8s 集群能够访问外部服务的网络和端口
  2. 权限配置:每个业务命名空间都需要配置 Role 和 RoleBinding
  3. 标签统一:保持所有监控组件的标签一致性,方便管理和查询
  4. 环境区分:通过 platform 标签区分开发、测试、生产环境