用prometheus监控Nginx

GitHub上官方地址:https://github.com/knyar/nginx-lua-prometheus
告警规则地址:https://awesome-prometheus-alerts.grep.to/rules#nginx

1.nginx需要支持lua功能,若是使用openresty的话,则自带支持lua
2.把lua文件上传到服务器中,
3.修改nginx配置文件,加载lua功能

# cat nginx.conf
http {

  ......

  lua_shared_dict prometheus_metrics 10M;
  lua_package_path "/path/to/nginx-lua-prometheus/?.lua;;"; # lua文件存放路径
  init_worker_by_lua_block {
    prometheus = require("prometheus").init("prometheus_metrics")
    metric_requests = prometheus:counter(
      "nginx_http_requests_total", "Number of HTTP requests", {"host", "status"})
    metric_latency = prometheus:histogram(
      "nginx_http_request_duration_seconds", "HTTP request latency", {"host"})
    metric_connections = prometheus:gauge(
      "nginx_http_connections", "Number of HTTP connections", {"state"})
  }
  log_by_lua_block {
    metric_requests:inc(1, {ngx.var.server_name, ngx.var.status})
    metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name})
  }

  server {

    ......
    # 设置prometheus收集收据接口
    location /metrics {
      content_by_lua_block {
        metric_connections:set(ngx.var.connections_reading, {"reading"})
        metric_connections:set(ngx.var.connections_waiting, {"waiting"})
        metric_connections:set(ngx.var.connections_writing, {"writing"})
        prometheus:collect()
      }
    }
  }

}

4.先检测nginx配置文件,然后重启nginx,访问 http://ip:port/metrics
5.修改prometheus配置文件,加上监听nginx的配置

  - job_name: 'nginx'
    static_configs:
    - targets: ['localhost:80']

6.把nginx告警规则放在prometheus指定目录下

重启prometheus

7.grafana使用的模板
模板ID:10223
地址:https://grafana.com/grafana/dashboards/10223

另一种方式,参考网址:https://www.cnblogs.com/you-men/p/13173245.html

posted @   哈喽哈喽111111  阅读(1905)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2020-05-14 FastDFS与nginx配置使用的配置信息
点击右上角即可分享
微信分享提示