Python Requests主机不可达错误捕获与Nginx容器监控脚本优化
Nginx容器监控看门狗脚本问题及优化方案
问题说明
我正在编写一个监控Nginx容器的小型看门狗脚本,当前代码如下:
import requests import time url = 'http://localhost:1234/' response = '' def checkloop (url, response): try: response = requests.get(url) except requests.ConnectionError: print("Can't connect to the site, sorry") else: response.status_code == 200 print("OK", response.status_code) while response == '': checkloop (url, response) time.sleep(5)
但当主机宕机时,脚本会直接崩溃,无法正确捕获错误,抛出如下异常:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=1234): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10332e4c0>: Failed to establish a new connection: [Errno 61] Connection refused'))
我有两个需求:
- 请求返回非200状态码(如403、404等)时,能打印对应的错误码;
- 希望了解现成的Python看门狗工具或编写指南。
问题修复与优化
1. 完善错误捕获与状态码处理
原脚本存在几个明显问题:
- 函数内的
response是局部变量,外部的response不会被更新,导致循环永远无法终止; - 只捕获了
ConnectionError,但requests还有超时、DNS解析失败等其他异常类型; else块里的response.status_code == 200只是无效判断,无论状态码是什么都会打印"OK"。
修正后的代码如下:
import requests import time # 配置监控地址 MONITOR_URL = 'http://localhost:1234/' def check_nginx_status(): try: # 设置超时时间,避免请求挂起 response = requests.get(MONITOR_URL, timeout=5) # 主动触发HTTP错误(非200状态码会抛出异常) response.raise_for_status() print(f"[正常] Nginx服务可用,状态码: {response.status_code}") except requests.ConnectionError: print("[错误] 无法建立连接,主机可能宕机或Nginx容器未启动") except requests.HTTPError as e: print(f"[HTTP错误] 状态码: {e.response.status_code}, 详情: {str(e)}") except requests.Timeout: print("[错误] 请求超时,Nginx响应过慢") except Exception as e: print(f"[未知错误] {str(e)}") # 持续监控循环 while True: check_nginx_status() time.sleep(5)
2. 现成Python看门狗工具推荐
watchdog库:原本用于监控文件系统变化,可结合requests改造成服务监控工具,适合自定义扩展逻辑;monit(Python封装版):轻量级系统监控工具,支持进程、服务状态监控,自带成熟的告警机制;prometheus-client+Grafana:如果需要搭建专业监控体系,用prometheus-client暴露监控指标,搭配Grafana做可视化展示,适合生产环境;healthchecks:简单易用的健康检查工具,支持定时发送请求并记录状态,可配置邮件、即时通讯工具告警。
看门狗脚本编写要点
- 必须设置请求超时,避免脚本因请求挂起而卡住;
- 捕获多类型异常,不要只处理单一错误场景;
- 用日志文件替代控制台打印,方便后续排查问题;
- 加入告警机制(如邮件、企业微信通知),异常时及时推送消息;
- 避免硬编码配置,建议用配置文件或环境变量管理监控地址、检查间隔等参数。
内容的提问来源于stack exchange,提问作者flamixx
相关产品推荐
相关产品推荐

