在 AWS App Runner 上运行的 FastAPI 服务器在 24 小时后失败

Ste*_*nwo 3 python amazon-web-services gunicorn fastapi

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

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

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()
Run Code Online (Sandbox Code Playgroud)

Anu*_*Joy 7

我有同样的问题。经过大量的尝试和错误后,两项更改似乎为我解决了这个问题。

  1. 将 uvicorn 设置--timeout-keep-alive为 65。对于gunicorn,此参数为--keep-alive。我假设如果 uvicorn 在 ALB 之前关闭 tcp 套接字,应用程序负载均衡器将抛出 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 可能足以解决问题。