# 前提

这个项目是基于lua实现的,因此需要你的nginx支持了ngx_lua (opens new window)模块儿,如果不支持,则无法正常使用。

我这里使用自己封装好了的rpm包进行安装,如果你也需要,可直接用:制作openresty-rpm包 (opens new window)

# 快速配置

将代码拉到本地:

$ wget https://github.com/knyar/nginx-lua-prometheus/archive/refs/tags/0.20240525.zip
$ unzip 0.20240525.zip
$ mv nginx-lua-prometheus-0.20240525 /etc/nginx/lua

1
2
3

然后在Nginx的主配置的http区域添加如下内容:

    lua_shared_dict prometheus_metrics 10M;
    lua_package_path "/etc/nginx/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 {
        listen 9145;
        server_name _;
        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()
            }
        }
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

之后加载配置文件,会监听在9145端口。

请求验证一下:

$ curl localhost:9145/metrics
# HELP nginx_http_connections Number of HTTP connections
# TYPE nginx_http_connections gauge
nginx_http_connections{state="reading"} 0
nginx_http_connections{state="waiting"} 1
nginx_http_connections{state="writing"} 2
# HELP nginx_http_request_duration_seconds HTTP request latency
# TYPE nginx_http_request_duration_seconds histogram
nginx_http_request_duration_seconds_bucket{host="_",le="0.005"} 11
nginx_http_request_duration_seconds_count{host="_"} 11
nginx_http_request_duration_seconds_count{host="api.micai.online"} 1
nginx_http_request_duration_seconds_sum{host="_"} 0
nginx_http_request_duration_seconds_sum{host="api.micai.online"} 0.986
# HELP nginx_http_requests_total Number of HTTP requests
# TYPE nginx_http_requests_total counter
nginx_http_requests_total{host="_",status="200"} 11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

然后就是配置该指标在Prometheus中的采集:

  - job_name: "openresty"
    metrics_path: '/metrics'
    static_configs:
      - targets: ['10.0.0.1:9145']
        labels:
          hostname: test-nginx-01
      - targets: ['10.0.0.2:9145']
        labels:
          hostname: test-nginx-02

1
2
3
4
5
6
7
8
9

# 其他配套

grafana大盘: 直接导入 462,如果感觉不够,还可以自行调整。

告警规则: 点我直达 (opens new window)