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