DEV Community

Cover image for Deploying FastAPI app with Google Cloud Run
Nari
Nari

Posted on • Edited on

Deploying FastAPI app with Google Cloud Run

Introduction

This post explains how to deploy a FastAPI app using Google Cloud Run.

Prerequisites

  • Google Cloud account
  • gcloud CLI
  • Docker
  • Python

Project setup

Create a FastAPI app using Poetry.

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

Create app/main.py

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

Edit main.py as follows

# 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

Run it in uvicorn

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

Google Cloud Run setup

If you have already installed gcloud CLI, update it as follows.

gcloud components update
Enter fullscreen mode Exit fullscreen mode

Connect the gcloud CLI to your GCP account.

gcloud auth login
Enter fullscreen mode Exit fullscreen mode

Set up your project ID

gcloud config set project PROJECT_ID
Enter fullscreen mode Exit fullscreen mode

Region settings

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

Docker settings

gcloud auth configure-docker
Enter fullscreen mode Exit fullscreen mode

Prepare Dockerfile in the same hierarchy as the app directory.

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

Prepare requirements.txt file for Dockerfile.
(In this case, use requirements.txt in the Dockerfile.)

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

Now that it is ready, deploy to Cloud Run.

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

If successful, it will be created with the name sample.
A URL will be created, so check the operation.


Conclusion

With the above, you can now deploy your FastAPI app to Google Cloud Run.

Although the details are omitted here, it would be a good idea to actually add CORS and headers in middleware and implement an authentication function such as Firebase Authentication.

Note: The path to import must be specified from the app directory.

Example: app/lib/test.py

# app/main.py
from app.lib import test
Enter fullscreen mode Exit fullscreen mode

Top comments (0)