温馨提示×

如何监控debian nginx

小樊
51
2026-09-21 18:49:03
栏目: 智能运维

在 Debian 上“监控 Nginx”通常分三层:进程/服务是否活着、运行状态与性能、业务/访问日志与告警。下面按从简到繁给你一套可落地的做法。


一、基础:确认 Nginx 是否在运行

1. 查看服务状态(systemd)

systemctl status nginx

或

service nginx status

开机自启:

systemctl enable nginx

2. 查看进程

ps aux | grep nginx

3. 查看端口

ss -lntp | grep ':80\|:443'

二、开启 Nginx 状态监控(强烈推荐)

1. 启用 stub_status

编辑站点配置(如 /etc/nginx/sites-enabled/default):

server {
    listen 80;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        allow 127.0.0.1;
        deny all;
    }
}

测试并重载:

nginx -t
systemctl reload nginx

访问:

curl http://127.0.0.1/nginx_status

输出示例:

Active connections: 12
server accepts handled requests
 1000 1000 2500
Reading: 0 Writing: 1 Waiting: 11

指标含义:

  • Active connections:当前连接数
  • accepts / handled:总接受 / 成功连接
  • requests:总请求数
  • Reading / Writing / Waiting

三、系统级监控(CPU、内存、连接)

1. 实时查看

top -p $(pgrep nginx)
htop

2. 网络连接数

ss -s

3. 文件描述符

cat /proc/$(pgrep nginx | head -1)/limits

四、日志监控(访问 & 错误)

1. 实时看访问日志

tail -f /var/log/nginx/access.log

2. 错误日志

tail -f /var/log/nginx/error.log

3. 常见分析

# 状态码统计
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -nr

# top IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head

五、自动告警(服务挂了自动发现)

1. 最简单:cron + curl

* * * * * curl -sf http://127.0.0.1/nginx_status || systemctl restart nginx

2. 使用 monit(推荐)

安装:

apt install monit

示例 /etc/monit/conf.d/nginx:

check process nginx with pidfile /run/nginx.pid
    start program = "/usr/sbin/service nginx start"
    stop program  = "/usr/sbin/service nginx stop"
    if failed host 127.0.0.1 port 80 protocol http then restart
systemctl restart monit

六、专业监控方案(生产环境)

方案 A:Prometheus + Node Exporter + Nginx Exporter

  • nginx-prometheus-exporter
  • Grafana 看板

方案 B:Zabbix

  • 使用 Zabbix Nginx 模板

方案 C:Netdata(开箱即用)

bash <(curl -Ss https://my-netdata.io/kickstart.sh)

浏览器访问 http://IP:19999


七、常见监控指标建议

✅ 必须关注:

  • Nginx 进程是否存在
  • 5xx 错误率
  • 活跃连接数
  • 请求延迟
  • 磁盘空间(日志)

⚠️ 预警阈值示例:

  • 5xx > 1%
  • 连接数 > 80% 最大
  • 磁盘 > 85%

如果你愿意,我可以:

  • 给你一份 systemd + 邮件告警脚本
  • 或帮你 配置 Prometheus + Grafana
  • 或针对 WordPress / 反向代理 / 高并发场景定制监控

你现在是个人服务器还是生产环境?

0 踩