FastAPI is a modern Python framework for building APIs quickly with automatic docs and async support. Google Cloud Run offers a fully managed way to deploy containerized apps that scale to zero and run only when needed — perfect for FastAPI. Let’s walk through deploying a FastAPI app on Cloud Run step by step.
Step 1: Build a Basic FastAPI App
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello from FastAPI on Cloud Run!"}
Step 2: Add a Requirements File
# requirements.txt
fastapi
uvicorn[standard]
Step 3: Create a Dockerfile
# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
Step 4: Deploy to Cloud Run
- Install and initialize the Google Cloud SDK if you haven’t already.
- Make sure billing is enabled and a project is selected.
- Enable the Cloud Run and Container Registry APIs.
gcloud builds submit --tag gcr.io/YOUR_PROJECT_ID/fastapi-app
gcloud run deploy fastapi-service \
--image gcr.io/YOUR_PROJECT_ID/fastapi-app \
--platform managed \
--region us-central1 \
--allow-unauthenticated
You’ll get a live URL to your deployed FastAPI service!
Benefits of Using Cloud Run for FastAPI
- Scales to zero when not in use
- Automatic HTTPS
- No need to manage servers
- Works well with async apps
Optional: Add CORS, Logging, or Auth
You can enhance your API with fastapi.middleware.cors
, use structured logs for better observability in GCP, or add IAM-based access control.
Conclusion
Google Cloud Run is a great platform for deploying FastAPI apps with minimal infrastructure overhead. Whether you’re building microservices or backend APIs, the serverless nature of Cloud Run keeps your workflow clean and scalable.
If this helped, feel free to support future content: buymeacoffee.com/hexshift