You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI后台任务在Elastic Beanstalk上触发502 Bad Gateway错误排查求助

FastAPI后台任务在Elastic Beanstalk上触发502 Bad Gateway错误排查求助

我用FastAPI写了一个REST API,不管是本地运行还是部署在Elastic Beanstalk上,大部分功能都完全正常。但有一个启动后台任务的端点总是会返回502 Bad Gateway错误——这个后台任务生成PDF大概要30秒。

我本来以为是nginx的自动超时问题,已经在.platform/nginx/conf.d/myconfig.conf里把所有超时都设成了600,还在Procfile里给Gunicorn加了--timeout 300参数,但还是没解决问题。

本地运行的时候这个流程完全没问题,只有在EB上才会出问题。我的EB环境是基于Amazon Linux的。

下面是和这个问题相关的三个函数:

# 这是后台任务
async def generate_pdf_task(order_id: str):
    print("Generating PDF for order", order_id)
    
    # 这是一个需要约30秒来生成PDF的后台任务

    pdf_url = await upload_file(f"orders/{order_id}.zip", zip_buffer)

    # 更新订单的PDF URL
    await update_order(order_id, pdf_url)
    print(f"✅ PDF available at: {pdf_url}")

# 总是触发502错误的端点
@router.post("/generate-pdf/{order_id}")
async def generate_pdf(order_id: str, background_tasks: BackgroundTasks):
    print("Task started")
    background_tasks.add_task(generate_pdf_task, order_id)
    return {"message": "PDF generation started"}

# 用于轮询的函数
@router.get("/get-pdf-url/{order_id}")
async def get_pdf_url(order_id: str):
    print("Checking PDF status")
    order = await fetch_order(order_id)
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
    return {"pdf_url": order.get('pdf_url')}

前端通常能以5秒为间隔调用get_pdf_url三次,之后就会超时。有没有人知道怎么解决这个问题?

备注:内容来源于stack exchange,提问作者rxnen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:33:03