Google Cloud Run部署Python Flask API遇实例启动超时问题求助
Cloud Run部署Flask API启动实例后无法正常响应请求问题
我在Google Cloud Run中部署了一个Flask应用作为API服务。当Cloud Run启动新实例处理API请求时,该Flask应用无法正常响应请求,但从Cloud Run控制台日志来看,应用似乎已成功启动。
Cloud Run控制台日志片段
2024-04-03 19:30:57.734 PDT [2024-04-04 02:30:57 +0000] [1] [INFO] Starting gunicorn 21.2.0 2024-04-03 19:30:57.735 PDT [2024-04-04 02:30:57 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) 2024-04-03 19:30:57.735 PDT [2024-04-04 02:30:57 +0000] [1] [INFO] Using worker: gthread 2024-04-03 19:30:57.757 PDT [2024-04-04 02:30:57 +0000] [2] [INFO] Booting worker with pid: 2 2024-04-03 19:30:58.672 PDT APP Loading: 0.8971238136291504 sec 2024-04-03 19:31:04.226 PDT [nltk_data] Downloading package punkt to /home/nltk_data... 2024-04-03 19:31:04.516 PDT [nltk_data] Unzipping tokenizers/punkt.zip. 2024-04-03 19:31:05.829 PDT [nltk_data] Downloading package stopwords to /home/nltk_data... 2024-04-03 19:31:05.908 PDT [nltk_data] Unzipping corpora/stopwords.zip. 2024-04-03 19:31:08.050 PDT STARTUP HTTP probe succeeded after 3 attempts for container "backend-1" on path "/". 2024-04-03 19:31:54.527 PDT GET 504 713 B 60 s Chrome 123 https://backend-uw.a.run.app/reports?user=12345
main.py代码片段
import time __init_time = time.time() import json import logging import os import shutil from threading import Thread import uuid from flask import Flask from flask import request from flask import abort from flask import jsonify from flask import Response from flask_cors import CORS from lazy_import import lazy_class # 延迟加载耗时较长的模块,以降低后端应用加载延迟 GptController = lazy_class( 'controls.gpt_controller.GptController') DocumentsController = lazy_class( 'controls.documents_controller.DocumentsController') FirestoreController = lazy_class( 'controls.firestore_controller.FirestoreController') UserController = lazy_class( 'controls.user_controller.UserController') Utilities = lazy_class( 'utils.utilities.Utilities') logging.getLogger('requests').setLevel(logging.ERROR) logging.getLogger('httpx').setLevel(logging.ERROR) TEMP_FOLDER = 'temp' app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' # 初始化应用时创建所需文件夹 os.makedirs( os.path.join(app.instance_path, TEMP_FOLDER), exist_ok=True) @app.route("/", methods=["GET"]) def home(): """Cloud Run启动健康检查的入口路由""" __time = time.time() while (time.time()-__time) < 10: try: if FirestoreController().firestore_client: return "<h1>App Alive</h1>" except Exception as _: pass time.sleep(0.5) abort(500, 'Server not ready') @app.route("/reports", methods=["GET"]) def report_operations(): """ 处理'report'相关API操作的入口函数 """ return { "status": "success" } print(f'APP Loading: {time.time() - __init_time} sec') if __name__ == "__main__": app.run( debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)) )
Dockerfile代码
FROM python:3.9 # 允许日志信息立即出现在Knative日志中 ENV PYTHONUNBUFFERED True # 将本地代码复制到容器镜像中 ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # 安装Python依赖 RUN python -m venv xplor-env ENV PATH="xplor-env/bin:$PATH" RUN pip install --upgrade pip RUN pip install gunicorn RUN pip install -r requirements.txt CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app
已采取的优化措施
- 使用懒加载将应用加载延迟降至约1秒
- 在应用的
/路由添加了HTTP启动健康检查探针
内容的提问来源于stack exchange,提问作者splashmonkey
相关产品推荐
相关产品推荐

