nginx在云原生中需通过nginx-prometheus-exporter或lua-resty-prometheus暴露prometheus指标,再配合service monitor(按标签匹配service、同命名空间部署)实现自动化监控,最后通过/targets验证抓取状态。

在云原生环境中,Nginx 本身不直接暴露 Prometheus 兼容指标,需借助 Exporter 或探针桥接;Service Monitor 是 Kubernetes 中用于声明式定义 Prometheus 抓取目标的 CRD 资源,它不与 Nginx 直接交互,而是通过识别符合规范的服务(Service)及其关联的 Pod,自动配置抓取任务。要实现 Nginx 的自动化监控,关键在于让 Nginx 实例“可被发现”且“可被采集”,Service Monitor 只是其中一环。
确保 Nginx 暴露标准指标接口
Nginx 原生不输出 Prometheus 格式指标,必须引入适配层:
- 部署 nginx-prometheus-exporter(推荐官方镜像
nginx/nginx-prometheus-exporter:0.9.0),以 sidecar 或独立 Pod 方式运行,监听 Nginx 的 stub_status 或 ngx_http_v2_module 状态页,并转换为/metrics接口 - 若使用 OpenResty,可集成 lua-resty-prometheus 库,在 Lua 层直接埋点并暴露指标
- 所有指标必须满足 Prometheus 文本格式规范,例如:
# TYPE nginx_http_requests_total counter<br>nginx_http_requests_total{host="example.com",status="200"} 1245
构建可被 Service Monitor 发现的服务拓扑
Service Monitor 不扫描 Pod,而是监听 Service 对象及其标签选择器。需按以下方式组织资源:
- 为运行 exporter 的 Pod 添加标签,如
app: nginx-exporter - 创建一个 Service(类型 ClusterIP),selector 匹配上述标签,并开放 exporter 的端口(默认
9113) - 该 Service 不需要 ClusterIP 可达性,只需存在且带正确 label,Service Monitor 才能将其纳入发现范围
- 确保 Service 和 Service Monitor 处于同一命名空间(或 Service Monitor 配置了跨命名空间权限)
编写并部署 Service Monitor 资源
Service Monitor 是自定义资源,需明确指定目标服务、端口和抓取路径:
- 定义
namespaceSelector控制监控范围(如只选default) - 用
selector.matchLabels匹配上一步中 Service 的标签 - 设置
endpoints.port为 Service 暴露的指标端口(如9113) - 可选配
endpoints.path(默认/metrics)和interval(如30s) - 应用后,Prometheus Operator 会自动更新 Prometheus 的 scrape_configs
验证与调试要点
Service Monitor 生效后,需逐层确认链路通畅:
- 检查
kubectl get servicemonitor -n monitoring是否处于 Active 状态 - 进入 Prometheus Pod,查看
/targets页面,确认对应 job 出现且状态为 UP - 访问该 target 的
/metrics地址,确认返回内容为合法 Prometheus 文本格式 - 注意:Service Monitor 不支持
kube-system和monitoring命名空间内的 Service,如需监控这些空间中的 Nginx 组件,应改用 PodMonitor 或 AdditionalScrapeConfigs











