Skip to content
Raisalon

Machine Learning

Deploy a machine learning model with FastAPI and Docker

Serve a scikit-learn model as a validated REST API: load it once with a lifespan handler, test it with TestClient, and package it in a cache-friendly Docker image.

Author
3 min read

A trained model in a notebook helps nobody until another system can call it. The usual first step is an HTTP API: send features as JSON, get a prediction back. This guide serves a scikit-learn model with FastAPI, validates every input, tests the endpoint, and packages it in a Docker image. Every Python file below was run with Python 3.13, FastAPI 0.165, scikit-learn 1.9 and joblib 1.6.

The project has four files:

train.py
requirements.txt
Dockerfile
app/
  main.py
  model.joblib   (created by train.py)

Train and save the model

The model is a scaler and logistic regression in one scikit-learn pipeline, so preprocessing travels with the model and cannot drift apart from it at serving time.

from pathlib import Path

import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print(f"test accuracy: {model.score(X_test, y_test):.3f}")

Path("app").mkdir(exist_ok=True)
joblib.dump(model, "app/model.joblib")

Running it prints test accuracy: 0.921. One rule matters here: load the model with the same scikit-learn version that saved it. scikit-learn does not support loading a persisted model across versions, so pin the version in requirements.txt. scikit-learn model persistence

Serve it with FastAPI

Loading the model on every request would be slow. FastAPI’s lifespan handler runs code once before the application starts serving and again when it shuts down, which is the recommended place to load ML models. FastAPI lifespan events Pydantic models describe the request and response, so invalid input is rejected before it reaches the model.

from contextlib import asynccontextmanager
from pathlib import Path

import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field

MODEL_PATH = Path(__file__).parent / "model.joblib"
CLASS_NAMES = ["setosa", "versicolor", "virginica"]
models = {}


@asynccontextmanager
async def lifespan(app: FastAPI):
    models["iris"] = joblib.load(MODEL_PATH)  # once, before the first request
    yield
    models.clear()


app = FastAPI(title="Iris classifier", lifespan=lifespan)


class Flower(BaseModel):
    sepal_length: float = Field(gt=0, le=20, description="cm")
    sepal_width: float = Field(gt=0, le=20, description="cm")
    petal_length: float = Field(gt=0, le=20, description="cm")
    petal_width: float = Field(gt=0, le=20, description="cm")


class Prediction(BaseModel):
    species: str
    probability: float


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}


@app.post("/predict")
def predict(flower: Flower) -> Prediction:
    features = [[flower.sepal_length, flower.sepal_width,
                 flower.petal_length, flower.petal_width]]
    probabilities = models["iris"].predict_proba(features)[0]
    best = int(probabilities.argmax())
    return Prediction(species=CLASS_NAMES[best],
                      probability=round(float(probabilities[best]), 4))

The predict function is a plain def, not async def. Model inference is CPU work that blocks, and FastAPI runs plain functions in a thread pool so they do not stall the event loop. The Field limits turn nonsense such as a negative petal length into an automatic 422 response with a clear error message. FastAPI also generates interactive documentation at /docs from these types.

Test the endpoint before you ship it

FastAPI’s TestClient calls the app in-process, with no server running. Using it in a with block runs the lifespan handler, so the model is loaded exactly as in production. With the FastAPI version used here, the test client needs the httpx2 package; older releases used httpx.

from fastapi.testclient import TestClient

from app.main import app


def test_predict_and_validation():
    with TestClient(app) as client:  # "with" runs the lifespan, loading the model
        assert client.get("/health").json() == {"status": "ok"}

        ok = client.post("/predict", json={
            "sepal_length": 5.1, "sepal_width": 3.5,
            "petal_length": 1.4, "petal_width": 0.2,
        })
        assert ok.status_code == 200
        assert ok.json()["species"] == "setosa"

        bad = client.post("/predict", json={
            "sepal_length": -1, "sepal_width": 3.5,
            "petal_length": 1.4, "petal_width": 0.2,
        })
        assert bad.status_code == 422

The valid request returns {"species": "setosa", "probability": 0.9811} and the invalid one returns status 422. Run the test with pytest in CI so a change to the model or schema that breaks the contract fails the build.

Advertisement

Package it with Docker

Pin the exact versions you trained and tested with. The standard extra installs the fastapi command used to run the server.

fastapi[standard]==0.165.0
scikit-learn==1.9.1
joblib==1.6.0

The Dockerfile follows the structure FastAPI recommends. FastAPI in containers

FROM python:3.13-slim

WORKDIR /code

# Dependencies first: this layer is cached until requirements.txt changes.
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

# Application code and model last, because they change most often.
COPY ./app /code/app

# Exec form, so the server shuts down gracefully and lifespan cleanup runs.
CMD ["fastapi", "run", "app/main.py", "--port", "80"]

Three details carry most of the value:

  • Copy requirements before the code. The requirements file rarely changes, so Docker reuses the cached dependency layer, and rebuilding after a code change takes seconds instead of reinstalling everything.
  • Use the exec form of CMD, the JSON array. FastAPI’s documentation says to always use it, so the server can shut down gracefully and lifespan events are triggered.
  • Match the Python version to training. Use the same Python and library versions in the image that produced the model file.

Build and run it:

docker build -t iris-api .
docker run -p 8000:80 iris-api

The API is then available at http://localhost:8000/predict, with documentation at http://localhost:8000/docs.

Production notes

  • Behind a TLS-terminating proxy such as Nginx or Traefik, add --proxy-headers to the command so the app trusts the proxy’s headers about HTTPS.
  • On Kubernetes, run a single server process per container and scale by adding replicas, rather than running several workers inside one container.
  • Avoid the old all-in-one base images. The former tiangolo/uvicorn-gunicorn-fastapi image is deprecated; building from the official Python image as above is the recommended approach.
  • Version the model with the code. Tag images with the model version, so every prediction can be traced back to the exact model that made it.

Next steps

Replace the iris model with your own pipeline, keep the schema strict, and add the test to CI before the first deploy. The case studies on this site, such as brain tumor detection from MRI scans, follow the same pattern of a model behind a separate API.

Share

Written by

Advertisement

Advertisement