Azure App Service部署Telegram Bot:容器因8000端口Ping超时250秒后停止
问题:Azure App Service部署Telegram Bot后约250秒停止工作
在Azure App Service上部署Telegram Bot,部署成功且初始运行正常,但约250秒后突然停止。已完成代码审查、部署设置检查、日志分析等排查操作,仍未找到问题根源,需解决以确保Bot持续运行。
相关代码片段
from pyrogram import Client, filters app = Client("abc_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token) # 处理/start命令 @app.on_message(filters.command("start")) def start_command(client, message): # 回复Hello message.reply_text("Hello!") # 运行Bot app.run()
Azure App Service日志流错误日志
2024-02-22T10:22:55.549Z ERROR - Container final17bot_0_9baf7 for site final17bot did not start within the expected time limit. Elapsed time = 247.9341095 sec 2024-02-22T10:22:55.556Z ERROR - Container final17bot_0_9baf7 didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging. 2024-02-22T10:22:55.600Z INFO - Stopping site final17bot because it failed during startup.
解决方案
核心原因
Azure App Service默认会对容器发送HTTP健康检查(目标端口8000),而Telegram Bot是基于长连接的后台服务,没有监听HTTP端口,导致健康检查失败,Azure强制停止容器。
解决步骤
禁用HTTP健康检查
- 进入Azure App Service控制台,打开「配置」>「常规设置」
- 找到「健康检查」选项,将「启用健康检查」设为「关闭」
- 保存设置并重启应用
添加HTTP健康检查服务(推荐生产环境使用)
如果需要保留健康检查机制,可以在Bot代码中启动一个轻量HTTP服务,监听8000端口响应检查请求:from pyrogram import Client, filters import threading from flask import Flask # 健康检查服务 health_app = Flask(__name__) @health_app.route('/') def health_check(): return "OK", 200 def run_health_server(): health_app.run(host='0.0.0.0', port=8000) # Telegram Bot初始化 tg_bot = Client("abc_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token) @tg_bot.on_message(filters.command("start")) def start_command(client, message): message.reply_text("Hello!") if __name__ == "__main__": # 后台启动健康检查服务 health_thread = threading.Thread(target=run_health_server) health_thread.daemon = True health_thread.start() # 启动Telegram Bot tg_bot.run()同时需在
requirements.txt中添加flask依赖。调整启动超时时间
- 进入Azure App Service「配置」>「常规设置」
- 找到「启动超时」,将默认值调整为300秒及以上,给Bot足够的启动初始化时间
内容的提问来源于stack exchange,提问作者Yeshpal Singh
相关产品推荐
相关产品推荐

