Skip to content

About

Production-grade FastAPI on GCP Cloud Run with Docker and GitHub Actions CI/CD

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

☁️ CloudDeployX

Production-grade FastAPI REST API — Containerized with Docker, deployed on Google Cloud Run, automated via GitHub Actions CI/CD.

CI/CD Python FastAPI Docker GCP License: MIT


Table of Contents


Architecture

  Developer  ──git push──▶  GitHub  ──triggers──▶  GitHub Actions
                                                          │
                                              ┌───────────┴──────────────┐
                                              │  1. Run tests (pytest)   │
                                              │  2. Build Docker image   │
                                              │  3. Push → Artifact Reg. │
                                              │  4. Deploy → Cloud Run   │
                                              └───────────┬──────────────┘
                                                          │
  End User  ──HTTPS──▶  Cloud Run URL  ◀─── Deployed ────┘
                              │
                    ┌─────────▼──────────┐
                    │  FastAPI Container  │
                    │  (Uvicorn + Python) │
                    └─────────┬──────────┘
                              │ stdout logs
                    ┌─────────▼──────────┐
                    │   Cloud Logging     │
                    │   Cloud Monitoring  │
                    └────────────────────┘

Request Flow

  1. Client sends HTTPS request to the Cloud Run service URL
  2. Cloud Run routes it to an available container instance
  3. Uvicorn (ASGI server) processes the HTTP connection
  4. FastAPI matches the URL path to the correct router handler
  5. Handler executes logic, writes a structured JSON log to stdout
  6. Cloud Logging ingests the stdout log automatically
  7. FastAPI returns a JSON response with latency headers

Security Architecture

Layer Mechanism
GitHub → GCP Auth Workload Identity Federation (no static keys)
Image storage Private Artifact Registry (IAM-gated)
Runtime secrets Cloud Run environment variables / Secret Manager
HTTPS Enforced by Cloud Run (no plain HTTP)
Container user Non-root (appuser, UID 1001)
IAM Least-privilege service accounts per workload

Tech Stack

Category Technology
Language Python 3.12
Framework FastAPI + Uvicorn
Containerization Docker (multi-stage build)
Registry GCP Artifact Registry
Compute GCP Cloud Run (serverless)
CI/CD GitHub Actions
Logging Cloud Logging (structured JSON)
Monitoring Cloud Monitoring + Uptime Checks
IAM GCP Service Accounts + Workload Identity Federation

Project Structure

CloudDeployX/
├── .github/
│   └── workflows/
│       └── deploy.yml          # GitHub Actions CI/CD pipeline
├── app/
│   ├── __init__.py
│   ├── main.py                 # FastAPI app factory + middleware
│   ├── config.py               # Pydantic-settings environment config
│   ├── logger.py               # Structured JSON logger for Cloud Logging
│   ├── routers/
│   │   ├── health.py           # /health, /health/live, /health/ready
│   │   └── items.py            # CRUD endpoints for /api/v1/items
│   └── models/
│       └── item.py             # Pydantic request/response models
├── tests/
│   └── test_main.py            # Async pytest test suite (9 tests)
├── Dockerfile                  # Multi-stage production Dockerfile
├── .dockerignore
├── .env.example                # Environment variable reference
├── .gitignore
├── requirements.txt
└── requirements-dev.txt

API Endpoints

Health

Method Path Description
GET / API root — service info
GET /health Health check with version info
GET /health/live Kubernetes/Cloud Run liveness probe
GET /health/ready Readiness probe with uptime

Items CRUD

Method Path Description
POST /api/v1/items Create a new item
GET /api/v1/items List all items
GET /api/v1/items/{id} Get single item
PUT /api/v1/items/{id} Update an item
DELETE /api/v1/items/{id} Delete an item

Interactive API docs: https://<your-cloud-run-url>/docs

Example: Create an item

curl -X POST https://<your-cloud-run-url>/api/v1/items \
  -H "Content-Type: application/json" \
  -d '{
    "name": "MacBook Pro",
    "description": "16-inch M3 Pro laptop",
    "price": 2499.99,
    "in_stock": true
  }'

Response:

{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "name": "MacBook Pro",
  "description": "16-inch M3 Pro laptop",
  "price": 2499.99,
  "in_stock": true,
  "created_at": "2025-01-15T10:30:00Z",
  "updated_at": "2025-01-15T10:30:00Z"
}

Local Development

Prerequisites

  • Python 3.12+
  • Docker Desktop
  • Git

1. Clone the repository

git clone https://github.com/Mukunth1004/CloudDeployX.git
cd CloudDeployX

2. Create virtual environment

python -m venv .venv
source .venv/bin/activate       # Linux/Mac
# .venv\Scripts\activate         # Windows

3. Install dependencies

pip install -r requirements-dev.txt

4. Configure environment

cp .env.example .env
# Edit .env with your values

5. Run the app

uvicorn app.main:app --host 0.0.0.0 --port 8080 --reload

App is running at http://localhost:8080 Docs at http://localhost:8080/docs

6. Run tests

pytest tests/ -v

Docker

Build the image

docker build -t clouddeployx:local .

Run locally

docker run -p 8080:8080 \
  -e APP_ENV=development \
  -e LOG_FORMAT=text \
  clouddeployx:local

Test the container

curl http://localhost:8080/health

GCP Setup

Complete step-by-step setup to connect this repo to Google Cloud.

Step 1 — Create a GCP project

export PROJECT_ID="clouddeployx-prod"
gcloud projects create $PROJECT_ID
gcloud config set project $PROJECT_ID
gcloud billing projects link $PROJECT_ID --billing-account=YOUR_BILLING_ACCOUNT_ID

Step 2 — Enable required APIs

gcloud services enable \
  run.googleapis.com \
  artifactregistry.googleapis.com \
  cloudbuild.googleapis.com \
  logging.googleapis.com \
  monitoring.googleapis.com \
  iam.googleapis.com \
  iamcredentials.googleapis.com

Step 3 — Create Artifact Registry repository

gcloud artifacts repositories create clouddeployx-repo \
  --repository-format=docker \
  --location=us-central1 \
  --description="CloudDeployX Docker images"

Step 4 — Create CI/CD service account

gcloud iam service-accounts create github-actions-sa \
  --display-name="GitHub Actions CI/CD Service Account"

SA_EMAIL="github-actions-sa@${PROJECT_ID}.iam.gserviceaccount.com"

# Grant required roles
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/run.admin"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/artifactregistry.writer"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/iam.serviceAccountUser"

Step 5 — Set up Workload Identity Federation

# Create WIF pool
gcloud iam workload-identity-pools create "github-pool" \
  --project="${PROJECT_ID}" \
  --location="global" \
  --display-name="GitHub Actions Pool"

# Create WIF provider
gcloud iam workload-identity-pools providers create-oidc "github-provider" \
  --project="${PROJECT_ID}" \
  --location="global" \
  --workload-identity-pool="github-pool" \
  --display-name="GitHub Provider" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository" \
  --issuer-uri="https://token.actions.githubusercontent.com"

# Allow GitHub Actions to impersonate the service account
gcloud iam service-accounts add-iam-policy-binding "${SA_EMAIL}" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)')/locations/global/workloadIdentityPools/github-pool/attribute.repository/Mukunth1004/CloudDeployX"

Step 6 — Add GitHub Secrets

Go to your repo → Settings → Secrets and variables → Actions and add:

Secret Name Value
GCP_PROJECT_ID clouddeployx-prod
WIF_PROVIDER projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool/providers/github-provider
WIF_SERVICE_ACCOUNT github-actions-sa@clouddeployx-prod.iam.gserviceaccount.com

CI/CD Pipeline

Every push to main triggers this workflow automatically:

git push → main
     │
     ├─ Job: test
     │     ├─ Checkout code
     │     ├─ Set up Python 3.12
     │     ├─ pip install requirements-dev.txt
     │     ├─ ruff check (linter)
     │     └─ pytest tests/ (9 tests)
     │
     └─ Job: deploy (only if tests pass)
           ├─ Authenticate to GCP (Workload Identity)
           ├─ Configure Docker for Artifact Registry
           ├─ docker build (multi-stage, cached)
           ├─ docker push :SHA + :latest
           └─ gcloud run deploy (zero-downtime rollout)

Pull requests only run the test job — no deployment.


Monitoring & Logging

Structured JSON Logs

Every request produces a structured log visible in Cloud Logging:

{
  "timestamp": "2025-01-15T10:30:00.123Z",
  "severity": "INFO",
  "message": "POST /api/v1/items → 201",
  "service": "clouddeployx",
  "version": "1.0.0",
  "environment": "production",
  "method": "POST",
  "path": "/api/v1/items",
  "status_code": 201,
  "latency_ms": 12.4
}

View logs in Cloud Console

gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=clouddeployx" \
  --limit=50 \
  --format=json

Set up uptime check

gcloud monitoring uptime create \
  --display-name="CloudDeployX Uptime" \
  --resource-type=uptime-url \
  --hostname=<your-cloud-run-url> \
  --path=/health/live \
  --period=60

Security

Practice Implementation
No static GCP keys Workload Identity Federation
Least-privilege IAM Separate service accounts per role
No secrets in images Runtime env vars via Cloud Run
Non-root container appuser (UID 1001)
HTTPS only Enforced by Cloud Run
Secrets management Cloud Secret Manager (ready to integrate)
Private image registry GCP Artifact Registry (IAM-controlled)

Troubleshooting

Container crashes on startup

# Check Cloud Run logs
gcloud logging read "resource.type=cloud_run_revision" --limit=20

Permission denied pushing to Artifact Registry

# Re-run Docker auth configuration
gcloud auth configure-docker us-central1-docker.pkg.dev

GitHub Actions auth fails

Verify the WIF provider audience and the attribute.repository value matches exactly Mukunth1004/CloudDeployX.

App returns 500 errors

Check structured logs in Cloud Logging Console under Logs Explorer:

resource.type="cloud_run_revision"
severity=ERROR

Resume Bullets

• Architected and deployed a production FastAPI REST API on Google Cloud Run
  using Docker multi-stage builds, reducing image size by 60% vs naive builds.

• Implemented a zero-downtime GitHub Actions CI/CD pipeline that builds,
  tests, and deploys on every push to main using Workload Identity Federation
  (no static credentials).

• Configured GCP IAM with least-privilege service accounts, Artifact Registry
  for private image storage, and structured JSON logging integrated with
  Cloud Logging and Cloud Monitoring.

• Achieved auto-scaling from 0 to 10 Cloud Run instances with 80 concurrent
  requests per instance, supporting burst traffic at zero idle cost.

License

MIT © Mukunth1004

About

Production-grade FastAPI on GCP Cloud Run with Docker and GitHub Actions CI/CD

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages