使

使用 Google Cloud Run 部署 FastAPI 应用

2025-06-08

使用 Google Cloud Run 部署 FastAPI 应用

介绍

这篇文章解释了如何使用 Google Cloud Run 部署 FastAPI 应用。

先决条件

  • Google Cloud 帐户
  • gcloud CLI
  • Docker
  • Python

项目设置

使用 Poetry 创建一个 FastAPI 应用程序。

pip install poetry
poetry new sample
cd sample
mv sample app
cd app
poetry add fastapi
poetry add 'uvicorn[standard]'
Enter fullscreen mode Exit fullscreen mode

创建 app/main.py

touch app/main.py
Enter fullscreen mode Exit fullscreen mode

编辑main.py如下

# main.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/", tags=["root"])
async def root():
    return {"message": "Hello World"}
Enter fullscreen mode Exit fullscreen mode

在 uvicorn 中运行

poetry shell
uvicorn app.main:app --reload
Enter fullscreen mode Exit fullscreen mode

Google Cloud Run 设置

如果您已经安装了 gcloud CLI,请按如下方式更新它。

gcloud components update
Enter fullscreen mode Exit fullscreen mode

将 gcloud CLI 连接到您的 GCP 帐户。

gcloud auth login
Enter fullscreen mode Exit fullscreen mode

设置您的项目 ID

gcloud config set project PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

区域设置

gcloud config set run/region REGION
Enter fullscreen mode Exit fullscreen mode

Docker 设置

gcloud auth configure-docker
Enter fullscreen mode Exit fullscreen mode

在与应用程序目录相同的层次结构中准备 Dockerfile。

FROM python:3.11.3
ENV PYTHONUNBUFFERED True

RUN pip install --upgrade pip
COPY requirements.txt .
RUN pip install --no-cache-dir -r  requirements.txt

ENV APP_HOME /root
WORKDIR $APP_HOME
COPY /app $APP_HOME/app

EXPOSE 8080
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]

Enter fullscreen mode Exit fullscreen mode

为 Dockerfile 准备 requirements.txt 文件。
(本例中使用 Dockerfile 中的 requirements.txt 文件。)

poetry export -f requirements.txt --output requirements.txt
Enter fullscreen mode Exit fullscreen mode

现在已准备就绪,请部署到 Cloud Run。

gcloud run deploy sample --port 8080 --source .
Enter fullscreen mode Exit fullscreen mode

如果成功,它将以名称 sample 创建。
同时会创建一个 URL,请检查操作。


结论

通过上述操作,您现在可以将您的 FastAPI 应用部署到 Google Cloud Run。

虽然这里省略了细节,但实际上在中间件中添加 CORS 和标头并实现诸如 Firebase 身份验证之类的身份验证功能是个好主意。

注意:必须从应用程序目录中指定导入的路径。

例如:app/lib/test.py

# app/main.py
from app.lib import test
Enter fullscreen mode Exit fullscreen mode
鏂囩珷鏉ユ簮锛�https://dev.to/0xnari/deploying-fastapi-app-with-google-cloud-run-13f3
PREV
使用 Sveltekit 创建 PWA | Svelte
NEXT
使用 ASS(Anchor、Solana 和 Svelte)的全栈 Web3 加速指南 🍑