使用 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]'
创建 app/main.py
touch app/main.py
编辑main.py如下
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/", tags=["root"])
async def root():
return {"message": "Hello World"}
在 uvicorn 中运行
poetry shell
uvicorn app.main:app --reload
Google Cloud Run 设置
如果您已经安装了 gcloud CLI,请按如下方式更新它。
gcloud components update
将 gcloud CLI 连接到您的 GCP 帐户。
gcloud auth login
设置您的项目 ID
gcloud config set project PROJECT_ID
区域设置
gcloud config set run/region REGION
Docker 设置
gcloud auth configure-docker
在与应用程序目录相同的层次结构中准备 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"]
为 Dockerfile 准备 requirements.txt 文件。
(本例中使用 Dockerfile 中的 requirements.txt 文件。)
poetry export -f requirements.txt --output requirements.txt
现在已准备就绪,请部署到 Cloud Run。
gcloud run deploy sample --port 8080 --source .
如果成功,它将以名称 sample 创建。
同时会创建一个 URL,请检查操作。
结论
通过上述操作,您现在可以将您的 FastAPI 应用部署到 Google Cloud Run。
虽然这里省略了细节,但实际上在中间件中添加 CORS 和标头并实现诸如 Firebase 身份验证之类的身份验证功能是个好主意。
注意:必须从应用程序目录中指定导入的路径。
例如:app/lib/test.py
# app/main.py
from app.lib import test