+91 99301 12627
MLOps & Cloud

How to Deploy a Machine Learning Model: FastAPI + Docker Step-by-Step

By Mehul Prajapati

Fibre optic cables in a data centre representing machine learning model deployment
On this page

Short answer: To deploy a machine learning model, (1) train it and save the full preprocessing-plus-model pipeline to a file, (2) wrap it in a web API such as FastAPI that accepts input and returns predictions, (3) package the API and its dependencies in a Docker container, (4) run that container on a server or managed cloud service (for example on AWS), and (5) monitor latency, errors and prediction quality over time. This turns a notebook model into a service other applications can use.

Key takeaways

  • Deploy the whole pipeline (preprocessing + model), not just the model object.
  • FastAPI is a popular, beginner-friendly Python framework for prediction APIs.
  • Docker makes your service run the same way on your laptop and in the cloud.
  • Validate inputs so bad data doesn’t crash or silently corrupt predictions.
  • Deployment isn’t the end: monitoring and retraining keep models useful.

Deployment patterns: which one do you need?

Pattern How it works Example
Real-time API Model answers each request instantly over HTTP Fraud check during payment
Batch prediction Model scores many records on a schedule Nightly churn scores for all customers
Streaming Model scores events as they arrive Live sensor anomaly detection
Embedded / edge Model runs on a device or in an app On-device image classification

This guide covers the most common beginner pattern: a real-time API.

Step 1: Train and save the full pipeline

# train.py
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv('churn.csv')
X = df[['tenure_months', 'monthly_charges', 'contract_type']]
y = df['churned']

preprocess = ColumnTransformer([
    ('num', StandardScaler(), ['tenure_months', 'monthly_charges']),
    ('cat', OneHotEncoder(handle_unknown='ignore'), ['contract_type']),
])
pipeline = Pipeline([('prep', preprocess),
                     ('model', RandomForestClassifier(random_state=42))])
pipeline.fit(X, y)
joblib.dump(pipeline, 'model.joblib')

Saving the pipeline ensures new data is transformed exactly as during training, which avoids a very common deployment bug. In a real project, evaluate on a held-out test set before saving.

Step 2: Serve predictions with FastAPI

# app.py
import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI(title='Churn Prediction API')
model = joblib.load('model.joblib')

class Customer(BaseModel):
    tenure_months: int = Field(ge=0)
    monthly_charges: float = Field(gt=0)
    contract_type: str

@app.get('/health')
def health():
    return {'status': 'ok'}

@app.post('/predict')
def predict(customer: Customer):
    X = pd.DataFrame([customer.model_dump()])
    proba = float(model.predict_proba(X)[0][1])
    return {'churn_probability': round(proba, 3)}

Run it locally with uvicorn app:app --reload and open http://127.0.0.1:8000/docs, where FastAPI generates interactive API documentation automatically. Pydantic validates inputs, so a negative tenure is rejected with a clear error.

Step 3: Pin your dependencies

# requirements.txt (pin the versions you trained with)
fastapi
uvicorn
scikit-learn
pandas
joblib

Pin exact versions (for example with pip freeze). A model saved with one Scikit-learn version may not load correctly in a different version.

Step 4: Containerise with Docker

# Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY model.joblib app.py ./
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
docker build -t churn-api .
docker run -p 8000:8000 churn-api

If it works in the container on your machine, it should behave the same on a server.

Step 5: Deploy to the cloud

Common options, from simplest to most flexible:

  • Managed container or app platforms: push your Docker image and the platform runs it (for example AWS App Runner or Amazon ECS, or similar services on other clouds)
  • Virtual machine: run the container on a cloud VM such as Amazon EC2 behind a web server
  • Managed ML platforms: services such as Amazon SageMaker provide model hosting endpoints with built-in scaling and monitoring options
  • Serverless functions: suitable for small, lightweight models with occasional traffic

Cloud services and pricing change, so follow the provider’s current documentation, and set budget alerts when you experiment.

Step 6: Secure, monitor and maintain

  • Security: require authentication (API keys or tokens), use HTTPS, and never put secrets in code or images
  • Logging: record requests, predictions, latency and errors (without sensitive personal data)
  • Monitoring: watch for data drift (input distributions changing) and performance decay
  • CI/CD: automate tests and builds with tools such as GitHub Actions
  • Versioning: track model versions so you can roll back quickly
  • Retraining: retrain on fresh data when performance drops

These practices are the core of MLOps. See What Is MLOps?

Common deployment mistakes

  • Deploying only the model and re-implementing preprocessing differently in the API
  • Unpinned library versions causing load errors or different predictions
  • No input validation
  • Loading the model on every request instead of once at startup
  • No monitoring, so the model silently degrades

Frequently asked questions

Is Flask or FastAPI better for ML deployment?

Both work. FastAPI is popular for new projects because of built-in data validation, automatic documentation and good performance.

Do I need Docker to deploy a model?

Not strictly, but Docker makes deployments reproducible and is widely used, so it’s worth learning.

Can I deploy a model for free?

Some platforms offer free tiers or credits suitable for learning projects. Check current terms, and set billing alerts on cloud accounts.

How is deploying an LLM app different?

The structure (API, container, monitoring) is similar, but LLM apps add prompt management, retrieval, token costs and output-quality evaluation. See the LLM Engineer Roadmap.

Is a deployed model a good portfolio project?

Yes. A live API with documentation and a short README shows skills many entry-level candidates lack. See more project ideas.

Conclusion

Deploying a machine learning model means saving the full pipeline, serving it through a validated API, packaging it with Docker, running it in the cloud and monitoring it over time. Do it once end to end with a simple model, and you’ll understand production ML far better than from notebooks alone. Need the modelling foundations first? Follow the Machine Learning Roadmap.

Learn ML deployment hands-on in our Machine Learning course, or talk to Mehul.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.