Azure容器应用中FastAPI接口Postman测试出现504网关超时问题
Azure容器应用FastAPI长接口504超时问题解决方案
问题根源
你的接口包含OpenAI等多API调用,处理时间长达数分钟,而Azure容器应用的网关、日志流存在默认超时限制,同时FastAPI的异步事件循环被同步任务阻塞,进一步加剧了超时问题。
具体解决方案
1. 调整Azure容器应用的请求超时
Azure容器应用的Ingress默认请求超时为4分钟,无法覆盖你的接口处理时长,需手动调整:
- 登录Azure门户,找到目标容器应用
- 进入「配置」→「入口」→「高级设置」
- 修改「请求超时」为足够大的值(例如
PT10M表示10分钟,格式遵循ISO 8601时长规范) - 保存配置并等待应用重启生效
2. 修复FastAPI异步事件循环阻塞问题
代码中的generate_first_image和generate_final_video是同步函数,会阻塞FastAPI的异步事件循环,拖慢请求处理速度。需将这些同步任务放到线程池执行:
import asyncio @app.post("/transcribe") async def transcribe(audio: UploadFile = File(...), song_name: str = Query(default=None), singer: str = Query(default=None)): log_event("INFO", f"New API call was made for song '{song_name}' by {singer}!") # 将同步函数包装到线程池,避免阻塞异步事件循环 await asyncio.to_thread(generate_first_image, song_name, singer) Transcription, duration_seconds, temp_audio_path = await audio_to_text(audio) log_event("INFO", f"Transcription: {Transcription}") frames_with_characters = await text_to_frames(Transcription, duration_seconds) log_event("INFO", f"Frames with characters: {frames_with_characters}") # 同样处理generate_final_video同步函数 video_path = await asyncio.to_thread(generate_final_video, frames_with_characters, temp_audio_path) os.remove(temp_audio_path) clean_temporary_storage() return FileResponse(path=video_path, media_type='video/mp4', filename="final_video.mp4")
3. 解决日志流中断问题
Azure实时日志流存在默认连接超时,长时间运行的任务会导致连接断开,但程序本身仍在正常运行。建议改用Azure Monitor日志查看完整历史日志:
- 进入容器应用的「监测」→「日志」
- 关联Log Analytics工作区(未关联则完成关联操作)
- 使用Kusto查询语句检索日志,示例:
ContainerAppConsoleLogs_CL | where ContainerAppName_s == "你的容器应用名称" | order by TimeGenerated desc
4. 超长时间任务的异步改造(可选)
如果接口处理时间超过15分钟,建议改为异步任务模式彻底规避网关超时:
- 接口接收请求后立即返回任务ID,后台通过任务队列(如Azure Queue Storage+自定义Worker、Celery+Azure Redis缓存)处理任务
- 用户通过任务ID轮询结果,或配置Webhook接收处理完成通知
内容的提问来源于stack exchange,提问作者Lee
相关产品推荐
相关产品推荐

