Prometheus是一款强大的开源监控系统,结合Nginx可以有效地监控Web服务器的性能指标。以下是实现Nginx监控的详细配置方案:
Nginx自带的stub_status
模块可以暴露基本的状态信息:
server {
listen 8080;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
访问http://localhost:8080/nginx_status
会返回类似:
Active connections: 2
server accepts handled requests
10 10 20
Reading: 0 Writing: 1 Waiting: 1
更推荐使用专门的Nginx Prometheus Exporter来暴露更丰富的指标:
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.11.0/nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
tar -xzf nginx-prometheus-exporter_*.tar.gz
./nginx-prometheus-exporter -nginx.scrape-uri=http://localhost:8080/nginx_status
http://localhost:9113/metrics
访问在Prometheus的配置文件中添加Nginx监控任务:
scrape_configs:
- job_name: 'nginx'
static_configs:
- targets: ['nginx-exporter:9113']
labels:
instance: 'production-nginx'
如果是Nginx Plus,可以使用更丰富的API:
server {
location /api {
api write=on;
}
location = /dashboard.html {
root /usr/share/nginx/html;
}
}
然后配置exporter使用API端点:
./nginx-prometheus-exporter -nginx.plus -nginx.scrape-uri=http://localhost:8080/api
可以通过Nginx的日志和Prometheus的Pushgateway或Grafana Loki来收集自定义指标:
log_format prometheus '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
server {
access_log /var/log/nginx/prometheus.log prometheus;
}
location /metrics {
allow 192.168.1.0/24;
allow 127.0.0.1;
deny all;
}
如果是Kubernetes环境,可以使用以下配置:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-exporter
spec:
template:
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
- name: exporter
image: nginx/nginx-prometheus-exporter:latest
args:
- -nginx.scrape-uri=http://localhost:8080/nginx_status
ports:
- containerPort: 9113
通过以上配置,您可以建立一个完整的Nginx监控系统,实时掌握Web服务器的运行状态和性能指标。