性能指标:
错误指标:
资源指标:
Prometheus + Grafana:
server {
listen 9113;
location /metrics {
stub_status on;
access_log off;
}
}
ELK Stack:
商业解决方案:
http {
server {
listen 8080;
location /nginx_status {
stub_status on;
access_log off;
allow 192.168.1.0/24;
deny all;
}
}
}
# 实时监控错误日志
tail -f /var/log/nginx/error.log | grep -E 'error|crit|alert|emerg'
# 实时统计HTTP状态码
tail -f /var/log/nginx/access.log | awk '{print $9}' | sort | uniq -c
location /lua_status {
content_by_lua_block {
ngx.say("Active connections: ", ngx.var.connections_active)
ngx.say("Reading: ", ngx.var.connections_reading)
ngx.say("Writing: ", ngx.var.connections_writing)
ngx.say("Waiting: ", ngx.var.connections_waiting)
}
}
Ansible Playbook示例:
- name: Configure Nginx Reverse Proxy
hosts: nginx_servers
tasks:
- name: Install Nginx
apt:
name: nginx
state: latest
- name: Deploy Nginx config
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
validate: 'nginx -t -c %s'
notify:
- Reload Nginx
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded
upstream backend {
server backend1.example.com max_fails=3 fail_timeout=30s;
server backend2.example.com max_fails=3 fail_timeout=30s;
# 自定义健康检查
check interval=5000 rise=2 fall=3 timeout=1000 type=http;
check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
动态DNS更新:
# 使用AWS CLI更新Route53
aws route53 change-resource-record-sets \
--hosted-zone-id Z1PA6795UKMFR9 \
--change-batch file://dns_update.json
Kubernetes Ingress自动扩展:
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: nginx-ingress
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx-ingress
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
# 使用split_clients实现流量分割
split_clients "${remote_addr}${http_user_agent}" $variant {
5% "v2";
95% "v1";
}
server {
location / {
if ($variant = "v2") {
proxy_pass http://backend_v2;
}
proxy_pass http://backend_v1;
}
}
# 使用Certbot自动续期证书
certbot renew --nginx --quiet --no-self-upgrade --post-hook "systemctl reload nginx"
# 基于Lua实现动态限流
lua_shared_dict my_limit_req_store 100m;
location /api/ {
access_by_lua_block {
local limit_req = require "resty.limit.req"
local lim, err = limit_req.new("my_limit_req_store", 100, 50)
if not lim then
ngx.log(ngx.ERR, "failed to instantiate a resty.limit.req object: ", err)
return ngx.exit(500)
end
local key = ngx.var.binary_remote_addr
local delay, err = lim:incoming(key, true)
if not delay then
if err == "rejected" then
return ngx.exit(503)
end
ngx.log(ngx.ERR, "failed to limit req: ", err)
return ngx.exit(500)
end
}
proxy_pass http://backend;
}
监控策略:
自动化原则:
安全考虑:
性能优化:
通过以上技术方案,可以构建一个高效、可靠的Nginx反向代理监控与自动化运维体系,显著提升系统稳定性和运维效率。