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

标签 python amazon-web-services gunicorn fastapi

我有一个使用 Gunicorn 配置的 FastAPI 服务器,部署在 AWS App Runner 上。当我尝试访问端点时,它运行良好,但是,24 小时后,当我尝试访问同一端点时,我收到 502 错误网关错误,此后 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()

最佳答案

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

  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 可能足以解决问题。

关于python - 在 AWS App Runner 上运行的 FastAPI 服务器在 24 小时后失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70611806/

相关文章:

python - 类型错误 : gradientDesc() takes exactly 1 argument (4 given)

python - gunicorn django 上的 CRITICAL WORKER TIMEOUT 错误

python - Gunicorn 双向 SSL 错误 "SSL_ERROR_UNKNOWN_CA_ALERT"

python - 在 Windows 10 VS2015 上使用 Python 和 GPU 支持构建和编译 OpenCV

python - 我怎样才能专注于python中列表的一个子集

python - Pygame在while true循环中显示图像内存问题

php - 如何调试 SSL https 挂起 ERR_CONNECTION_TIMED_OUT

python - 想要访问字典中位于另一个字典的列表内的值

amazon-web-services - FIlebeat-Redis-Logstash : Filebeat fast and Logstah slow, logstash 线程?

python - django + virtualenv + gunicorn - 没有名为 django.core.wsgi 的模块?