Deploying a FastAPI + PostgreSQL App Using Google Cloud Run and Cloud SQL

Combining FastAPI with PostgreSQL gives you a powerful backend stack. When you deploy it on Google Cloud Run and use Cloud SQL as your managed database, you get scalability, security, and ease of maintenance. This guide will show you how to deploy a containerized FastAPI app connected to a Cloud SQL PostgreSQL instance on Google Cloud. Step 1: Set Up Cloud SQL for PostgreSQL In the Google Cloud Console, go to SQL and create a new PostgreSQL instance. Set a root password and database name (e.g., appdb). Create a new user and allow connections from Cloud Run by enabling the Cloud SQL Admin API. Step 2: Create the FastAPI App # main.py from fastapi import FastAPI import psycopg2 import os app = FastAPI() @app.get("/") def read_root(): conn = psycopg2.connect( dbname=os.getenv("DB_NAME"), user=os.getenv("DB_USER"), password=os.getenv("DB_PASS"), host=os.getenv("DB_HOST"), ) cur = conn.cursor() cur.execute("SELECT NOW();") time = cur.fetchone() cur.close() conn.close() return {"db_time": time} Step 3: Requirements # requirements.txt fastapi uvicorn[standard] psycopg2-binary Step 4: 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 5: Deploy With Cloud SQL Proxy Sidecar You must connect Cloud Run securely to Cloud SQL using a Unix socket or TCP. Easiest way is to specify connection with an env var and bind it using --add-cloudsql-instances: gcloud builds submit --tag gcr.io/YOUR_PROJECT/fastapi-db-app gcloud run deploy fastapi-db-app \ --image gcr.io/YOUR_PROJECT/fastapi-db-app \ --add-cloudsql-instances=YOUR_PROJECT:REGION:INSTANCE_ID \ --set-env-vars DB_NAME=appdb,DB_USER=youruser,DB_PASS=yourpass,DB_HOST=/cloudsql/YOUR_PROJECT:REGION:INSTANCE_ID \ --platform managed \ --region us-central1 \ --allow-unauthenticated Security Tips Use Secret Manager for storing DB credentials securely. Limit DB user permissions to only necessary roles. Use Private IP connection to Cloud SQL for better security. Conclusion This stack gives you a powerful, serverless deployment of an async web app with a fully managed database. You get scalability, reduced operational burden, and seamless integration with Google Cloud tooling. If this helped, feel free to support my writing: buymeacoffee.com/hexshift

Apr 21, 2025 - 03:54
 0
Deploying a FastAPI + PostgreSQL App Using Google Cloud Run and Cloud SQL

Combining FastAPI with PostgreSQL gives you a powerful backend stack. When you deploy it on Google Cloud Run and use Cloud SQL as your managed database, you get scalability, security, and ease of maintenance. This guide will show you how to deploy a containerized FastAPI app connected to a Cloud SQL PostgreSQL instance on Google Cloud.

Step 1: Set Up Cloud SQL for PostgreSQL

  1. In the Google Cloud Console, go to SQL and create a new PostgreSQL instance.
  2. Set a root password and database name (e.g., appdb).
  3. Create a new user and allow connections from Cloud Run by enabling the Cloud SQL Admin API.

Step 2: Create the FastAPI App

# main.py
from fastapi import FastAPI
import psycopg2
import os

app = FastAPI()

@app.get("/")
def read_root():
    conn = psycopg2.connect(
        dbname=os.getenv("DB_NAME"),
        user=os.getenv("DB_USER"),
        password=os.getenv("DB_PASS"),
        host=os.getenv("DB_HOST"),
    )
    cur = conn.cursor()
    cur.execute("SELECT NOW();")
    time = cur.fetchone()
    cur.close()
    conn.close()
    return {"db_time": time}

Step 3: Requirements

# requirements.txt
fastapi
uvicorn[standard]
psycopg2-binary

Step 4: 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 5: Deploy With Cloud SQL Proxy Sidecar

You must connect Cloud Run securely to Cloud SQL using a Unix socket or TCP. Easiest way is to specify connection with an env var and bind it using --add-cloudsql-instances:

gcloud builds submit --tag gcr.io/YOUR_PROJECT/fastapi-db-app

gcloud run deploy fastapi-db-app \
  --image gcr.io/YOUR_PROJECT/fastapi-db-app \
  --add-cloudsql-instances=YOUR_PROJECT:REGION:INSTANCE_ID \
  --set-env-vars DB_NAME=appdb,DB_USER=youruser,DB_PASS=yourpass,DB_HOST=/cloudsql/YOUR_PROJECT:REGION:INSTANCE_ID \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated

Security Tips

  • Use Secret Manager for storing DB credentials securely.
  • Limit DB user permissions to only necessary roles.
  • Use Private IP connection to Cloud SQL for better security.

Conclusion

This stack gives you a powerful, serverless deployment of an async web app with a fully managed database. You get scalability, reduced operational burden, and seamless integration with Google Cloud tooling.

If this helped, feel free to support my writing: buymeacoffee.com/hexshift