Skip to main content

Command Palette

Search for a command to run...

πŸš€ Part 1: Preparing Your FastAPI + Scikit-Learn App for Deployment on Google Cloud Run

Published
β€’8 min readβ€’View as Markdown

🧠 Why FastAPI + Scikit-Learn + Google Cloud?

FastAPI gives us a blazing-fast way to expose machine learning models as APIs. With Google Cloud Run, we can deploy those APIs without managing servers, scaling automatically based on traffic.

In this guide, we walk through converting a local machine learning API into a production-ready cloud service β€” and it all begins with structuring your project.


πŸ—‚οΈ Project Structure

Make sure your folder (we named it ChurnAPI_test) contains the following files:

cssCopyEditChurnAPI_test/
β”œβ”€β”€ main.py
β”œβ”€β”€ model.joblib
β”œβ”€β”€ requirements.txt
└── Dockerfile

🧾 Step 1: Preparing main.py for Cloud Run

The main.py file is the heart of your FastAPI app. Here's a sample version adapted for Google Cloud Run:

pythonCopyEditimport uvicorn
import os
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import pandas as pd

app = FastAPI()

# Load the model
model = joblib.load("model.joblib")

# Define input schema
class Customer(BaseModel):
    data: dict

@app.post("/predict")
def predict(customer: Customer):
    try:
        df = pd.DataFrame([customer.data])
        prediction = model.predict(df)[0]
        probability = model.predict_proba(df)[0][1]
        return {
            "prediction": int(prediction),
            "churn_probability": round(probability, 3)
        }
    except Exception as e:
        return {"error": str(e)}

# βœ… Cloud Run entry point
if __name__ == "__main__":
    port = int(os.environ.get("PORT", 8080))
    uvicorn.run("main:app", host="0.0.0.0", port=port)

πŸ” Key differences from local testing is we include this part of code:

if name == "__main__":

port = int(os.environ.get("PORT", 8080))

uvicorn.run("main:app", host="0.0.0.0", port=port)

  • Uses host="0.0.0.0" (required by Docker)

  • Reads PORT from environment variable (used by Cloud Run)

  • No reload=True (that’s only for local development)


πŸ“„ Step 2: Create requirements.txt

Google Cloud needs to know which Python packages to install inside your Docker container. That’s where requirements.txt comes in.

βœ… Steps to Create It:

  1. In your project folder (ChurnAPI_test), create a new text file.

  2. Rename the file exactly to:

fastapi
uvicorn
pandas
joblib
scikit-learn

πŸ“Œ Add any extra libraries your model or code depends on (e.g., numpy, xgboost).


🐳 Step 3: Create Dockerfile

Docker lets us package our app, model, and dependencies into a portable container. Here’s the Dockerfile for our project:

βœ… How to Create a Dockerfile (Step-by-Step)

πŸ“ In your ChurnAPI_test project folder:

  1. Open Notepad or any plain text editor.

  2. Paste the following code (this is the full working version):

# Use official Python image
FROM python:3.10-slim

# Set working directory inside the container
WORKDIR /app

# Copy all files from your local folder into the container
COPY . .

# Install required Python packages
RUN pip install --no-cache-dir -r requirements.txt

# Expose port Cloud Run will use
ENV PORT 8080
EXPOSE 8080

# Start FastAPI app with uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

🐳 Full Dockerfile Explained (Line-by-Line)

This Dockerfile tells Google Cloud how to build and run your FastAPI + scikit-learn app inside a container. Below is the complete version with clear explanations for each step:

# βœ… Step 1: Start with a lightweight official Python 3.10 image
FROM python:3.10-slim

This pulls a minimal version of Python 3.10 as the base. The slim variant keeps the image small and fast, which is ideal for cloud deployments.


# βœ… Step 2: Set the working directory inside the container
WORKDIR /app

This creates a directory called /app inside the container and sets it as the working directory. All subsequent commands will run from here.


# βœ… Step 3: Copy all project files into the container
COPY . .

This copies everything from your local project folder (ChurnAPI_test) into the /app directory inside the container. That includes main.py, model.joblib, requirements.txt, and your Dockerfile itself.


# βœ… Step 4: Install the Python dependencies listed in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

This installs all the required Python packages inside the container.

  • The --no-cache-dir flag helps reduce the final image size.

# βœ… Step 5: Set the environment variable for the port (used by Cloud Run)
ENV PORT 8080
EXPOSE 8080

Google Cloud Run sends requests to your app through port 8080.

  • ENV PORT 8080 sets the environment variable.

  • EXPOSE 8080 tells Docker this is the port your app will listen on.


# βœ… Step 6: Start the FastAPI server using Uvicorn
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

This is the command Docker runs when your container starts.
It launches your FastAPI app using uvicorn, making it accessible publicly.

  • main:app β†’ main.py file and app = FastAPI()

  • --host 0.0.0.0 β†’ ensures the app listens to external traffic (not just localhost)

  • --port 8080 β†’ matches the port Cloud Run will send traffic to


βœ… Summary

This Dockerfile:

  • Sets up a clean Python environment

  • Installs your machine learning app's dependencies

  • Starts your FastAPI app correctly for production

Once built, this container can be deployed to any cloud platform, including Google Cloud Run, with no code changes.

πŸš€ Part 2: Setting Up Google Cloud SDK and CLI for FastAPI Deployment

In Part 1, we built a FastAPI app with a scikit-learn model, added a Dockerfile, and got everything ready for deployment. In this post, we’ll walk through how to set up Google Cloud CLI (gcloud) and prepare your environment to deploy that app to the cloud.

Let’s get started!


🧩 Step 1: Install the Google Cloud SDK

Google Cloud CLI is a command-line tool used to deploy, manage, and monitor services on Google Cloud.

πŸ”— Download and Install:

πŸ‘‰ https://cloud.google.com/sdk/docs/install

βœ… Follow the instructions for your operating system (Windows/macOS/Linux). After installing, open Command Prompt (or Terminal) and check if it's working:

gcloud --version

You should see the version number and some installed components.


πŸ” Step 2: Authenticate with Google Cloud

To link your terminal with your Google Cloud account, run:

gcloud auth login

This will:

  • Open a browser window

  • Ask you to log in to your Google account

  • Authenticate your terminal session with Google Cloud


πŸ—οΈ Step 3: Set Your Google Cloud Project

You must tell gcloud which project you're working on. Based on your dashboard, your Project ID is:

churnapi-456817

Run:

gcloud config set project churnapi-456817

βœ… This ensures all future commands (like build and deploy) apply to your churn project.


βš™οΈ Step 4: Enable Required Google Cloud Services

By default, services like Cloud Run and Cloud Build are not enabled. These must be turned on manually:

gcloud services enable run.googleapis.com
gcloud services enable cloudbuild.googleapis.com

πŸ’‘ Why?

ServiceWhy It's Needed
run.googleapis.comHosts your FastAPI container on Google Cloud Run
cloudbuild.googleapis.comBuilds your Docker image from your folder

Once enabled, you're ready to build and deploy πŸš€


🧭 Confirm Everything Is Set

You can confirm your project and services are configured by running:

gcloud config list

You should see:

[core]
project = churnapi-456817

And you're ready for deployment!

πŸš€ Part 3: Deploying Your FastAPI + Scikit-Learn App to Google Cloud Run

In Part 1, we prepared your FastAPI app and Dockerfile. In Part 2, we set up Google Cloud SDK and enabled required services. Now, in Part 3, we’ll build the container and deploy it to the cloud!

Let’s put your API into production.


πŸ—οΈ Step 1: Build and Submit Your Docker Image to Google Cloud

Make sure you're in your project folder that contains:

main.py
Dockerfile
requirements.txt
model.joblib

Then run this in your terminal:

cd C:\Users\nickolat\Desktop\ChurnAPI_test

Now build and upload your Docker image using Cloud Build:

gcloud builds submit --tag gcr.io/churnapi-456817/churn-api

πŸ” What this does:

  • Uses your Dockerfile to build an image

  • Tags it as churn-api

  • Uploads it to your Google Container Registry

Once it finishes, you'll see:

DONE
IMAGE: gcr.io/churnapi-456817/churn-api

βœ… You’ve now got a ready-to-deploy container!


πŸš€ Step 2: Deploy to Google Cloud Run

Now deploy your container to Cloud Run using this command:

gcloud run deploy churn-api \
  --image gcr.io/churnapi-456817/churn-api \
  --platform managed \
  --region asia-south1 \
  --allow-unauthenticated

πŸ’‘ Explanation:

OptionWhat it does
churn-apiThe name of your service
--imagePoints to your built Docker image
--platform managedUses the fully managed Cloud Run platform
--region asia-south1Deploys to the Mumbai region
--allow-unauthenticatedMakes your API publicly accessible

You’ll then see output like:

Service [churn-api] revision [churn-api-00001-xzy] has been deployed.
Service URL: https://churn-api-1069019972109.asia-south1.run.app

βœ… This is your live API URL!


πŸ” Step 3: Test Your API on the Web

Visit the Swagger UI:

πŸ‘‰ https://churn-api-1069019972109.asia-south1.run.app/docs

You’ll see an interactive interface where you can test the /predict endpoint.

πŸ” Sample JSON to Use:

jsonCopyEdit{
  "data": {
    "Online Security": "No",
    "Online Backup": "Yes",
    "Device Protection": "Yes",
    "Tech Support": "No",
    "Contract": "Month-to-month",
    "Paperless Billing": "Yes",
    "Payment Method": "Electronic check",
    "Married": "No",
    "Offer": "None",
    "Premium Tech Support": "No",
    "Unlimited Data": "Yes",
    "Internet Info": "Fiber Optic",
    "Revenue Category": "2000–5000",
    "Total Charges Category": "200–400",
    "Monthly Charge Category": "70–90",
    "Total Long Distance Charge Category": "0–20",
    "Avg Monthly GB Download Category": "20–40",
    "Age Category": "26–35",
    "Dependents_Category": "No",
    "Referrals_Category": "1–2",
    "Tenure_Category": "6–12 months"
  }
}

Hit β€œExecute” and you’ll get a prediction result and churn probability!


βœ… Final Thoughts

You’ve now:

  • Packaged your machine learning model

  • Deployed it with FastAPI inside a Docker container

  • Made it publicly accessible on Google Cloud Run

Your churn prediction API is now production-ready and can be called from anywhere β€” including your .NET frontend, mobile apps, or third-party tools.

More from this blog

Data Science

39 posts