【问题标题】:FastAPI server running on AWS App Runner fails after 24 hours在 AWS App Runner 上运行的 FastAPI 服务器在 24 小时后失败
【发布时间】:2022-01-06 18:21:18
【问题描述】:

我有一个使用 Gunicorn 配置的 FastAPI 服务器,部署在 AWS App Runner 上。当我尝试访问邮递员上的端点时,效果很好,但是,在 24 小时后,当我尝试访问同一个端点时,我收到 502 bad gateway 错误,并且在此之后 cloudWatch 上没有任何记录,直到我重新部署应用程序,然后它再次开始正常工作。

我怀疑这与我的 Gunicorn 配置本身有关,它在一段时间后以某种方式关闭了我的 API,而不是 AWS App Runner,但我还没有找到任何解决方案。我还在下面展示了我的 Gunicorn 设置。任何 hep 将不胜感激。

from fastapi import FastAPI
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from gunicorn.app.base import BaseApplication
import os
import multiprocessing

api = FastAPI()


def number_of_workers():
    print((multiprocessing.cpu_count() * 2) + 1)
    return (multiprocessing.cpu_count() * 2) + 1


class StandaloneApplication(BaseApplication):
    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {
            key: value for key, value in self.options.items()
            if key in self.cfg.settings and value is not None
        }
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


@api.get("/test")
async def root():
    return 'Success'


if __name__ == "__main__":
    if os.environ.get('APP_ENV') == "development":
        uvicorn.run("api:api", host="0.0.0.0", port=2304, reload=True)

    else:
        options = {
            "bind": "0.0.0.0:2304",
            "workers": number_of_workers(),
            "accesslog": "-",
            "errorlog": "-",
            "worker_class": "uvicorn.workers.UvicornWorker",
            "timeout": "0"
        }

        StandaloneApplication(api, options).run()

【问题讨论】:

    标签: python amazon-web-services gunicorn fastapi


    【解决方案1】:

    我遇到了同样的问题。经过大量的试验和错误,两个更改似乎为我解决了这个问题。

    1. 将 uvicorn --timeout-keep-alive 设置为 65。对于 gunicorn,此参数为 --keep-alive。如果 uvicorn 在 ALB 之前关闭 tcp 套接字,我假设 Application Load Balancer 会抛出 502。

    2. 将 App Runner 运行状况检查更改为使用 HTTP 而不是 TCP ping 来管理容器回收。目前,AWS UI 不允许您进行此更改。您必须使用 aws cli 执行此操作。使用任何活动的 URL 路径进行 ping 检查 - 在您的情况下为 /test

    aws apprunner update-service --service-arn <arn> --health-check-configuration Protocol=HTTP,Path=/test

    #2 可能足以解决问题。

    【讨论】:

    • #2 解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多