How to Build and Deploy a Machine Learning Model Using Python and Streamlit
A hands-on tutorial showing how to train a Scikit-learn model, build an interactive web application with Python and Streamlit, and deploy it cleanly with Docker.
One of the fastest ways to turn a Python machine learning model from a static notebook experiment into an interactive, stakeholder-ready web application is to deploy a machine learning model using Streamlit.
Whether you are building an internal credit-risk calculator, a clinical screening prototype, or a portfolio showcase for hiring managers, Streamlit lets Python engineers create clean, responsive data and ML interfaces in minutes—without writing separate HTML, CSS, and JavaScript boilerplate.
At RiteClick Technology, we have used Streamlit and containerised Python runtimes across multiple real-world builds—including our Loan Approval Prediction Application, Diabetes Prediction Application, and Spam SMS Classifier NLP. In this step-by-step tutorial, I show you how to structure, build, and deploy a production-ready Streamlit ML app cleanly.
Project Architecture: Separating Training from Serving
A common beginner mistake is re-training the machine learning model inside app.py every time a user clicks a button. That wastes CPU, slows down the UI, and produces inconsistent predictions.
Instead, separate your codebase cleanly into training and serving:
ml-streamlit-app/
├── artifacts/
│ └── model_pipeline.joblib # Serialized preprocessor + trained model
├── train_model.py # Offline training & evaluation script
├── app.py # Lightweight Streamlit inference UI
├── requirements.txt # Pinned Python dependencies
└── Dockerfile # Reproducible container deployment
Step 1: Train and Save a Complete Scikit-Learn Pipeline (train_model.py)
Always save the entire preprocessing and classification pipeline (ColumnTransformer + model) so user inputs in Streamlit receive identical scaling and encoding as training data:
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# Example tabular dataset loading
df = pd.read_csv("data/loan_applications.csv")
X = df[["applicant_income", "loan_amount", "credit_history", "dependents"]]
y = df["loan_approved"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
preprocessor = ColumnTransformer(
transformers=[
(
"num",
Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
]),
["applicant_income", "loan_amount", "credit_history", "dependents"],
)
]
)
pipeline = Pipeline(steps=[
("preprocessor", preprocessor),
("classifier", RandomForestClassifier(n_estimators=150, random_state=42)),
])
pipeline.fit(X_train, y_train)
print(f"Validation Accuracy: {pipeline.score(X_test, y_test):.3f}")
joblib.dump(pipeline, "artifacts/model_pipeline.joblib")
Step 2: Build the Interactive Streamlit App (app.py)
Notice three critical engineering practices in app.py below:
@st.cache_resourceloads the.joblibmodel once in memory rather than reloading from disk on every interaction.- Input bounds (
min_value,max_value) prevent impossible inputs (such as negative income). - Probability output (
predict_proba) gives decision-makers confidence scores, not just a blind binary label.
import joblib
import pandas as pd
import streamlit as st
st.set_page_config(
page_title="RiteClick Loan Risk Predictor",
page_icon="📊",
layout="centered",
)
@st.cache_resource
def load_model():
return joblib.load("artifacts/model_pipeline.joblib")
model = load_model()
st.title("Loan Approval Risk Predictor")
st.caption("Built with Python, Scikit-Learn & Streamlit — RiteClick Engineering Pattern")
with st.form("loan_prediction_form"):
col1, col2 = st.columns(2)
with col1:
income = st.number_input("Monthly Applicant Income", min_value=0.0, value=250000.0, step=10000.0)
dependents = st.number_input("Number of Dependents", min_value=0, max_value=15, value=1)
with col2:
loan_amount = st.number_input("Requested Loan Amount", min_value=1000.0, value=500000.0, step=25000.0)
credit_history = st.selectbox("Verified Credit History", options=[1, 0], format_func=lambda v: "Good Standing (1)" if v == 1 else "No / Poor History (0)")
submitted = st.form_submit_button("Evaluate Application", use_container_width=True)
if submitted:
input_df = pd.DataFrame([{
"applicant_income": income,
"loan_amount": loan_amount,
"credit_history": credit_history,
"dependents": dependents,
}])
prediction = int(model.predict(input_df)[0])
probability = float(model.predict_proba(input_df)[0][1])
if prediction == 1:
st.success(f"Low Risk — Likely Eligible (Approval Confidence: {probability * 100:.1f}%)")
else:
st.warning(f"Elevated Risk — Manual Review Recommended (Approval Confidence: {probability * 100:.1f}%)")

Using st.form(...) ensures the app only runs inference when the user clicks Evaluate Application, instead of re-executing on every keystroke.
Step 3: Pin Dependencies and Containerise with Docker
Always pin exact library versions in requirements.txt because scikit-learn models pickled in one version can fail to load in another:
streamlit==1.40.0
scikit-learn==1.5.2
pandas==2.2.3
joblib==1.4.2
Then package the app in a clean Dockerfile—the exact pattern we follow in our Heart Disease Prediction Dockerized ML project:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY artifacts/ ./artifacts/
COPY app.py .
EXPOSE 8501
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health || exit 1
ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
Step 4: Deployment Options (From Prototype to Production)
- Streamlit Community Cloud: Ideal for open-source portfolio demos—connect your GitHub repository and deploy in minutes.
- AWS ECS / EC2 + Docker + Nginx Reverse Proxy: Best for private enterprise tools requiring custom domain SSL, authentication, and VPC isolation.
- Decoupled Architecture (FastAPI + Laravel / Mobile): When you outgrow Streamlit and need multi-user RBAC, payment billing, or native mobile integration, move inference behind a FastAPI microservice while keeping the exact same
model_pipeline.joblibartifact.
For official configuration details, see the Streamlit Documentation and Docker Python Best Practices.
Security, Validation, and UX Polish Checklist for Streamlit Apps
Before sharing your deployed Streamlit URL with clients, recruiters, or internal staff, verify these five production details:
- Never Hardcode API Keys or Database Passwords: Store secrets in
.streamlit/secrets.tomllocally (excluded from Git via.gitignore) and inject environment variables in Docker/cloud hosting. - Validate Uploaded Files and Inputs: If your app accepts CSV uploads (for batch predictions), verify required column names, file size limits, and data types before running inference, displaying a clear user-friendly warning when columns are missing.
- Explain Predictions Clearly: Pair raw class predictions with confidence probabilities and simple plain-English guidance on what the result means.
- Optimise Memory Usage: Use
@st.cache_resourcefor ML models and@st.cache_data(ttl=3600)for reference datasets so concurrent users do not exhaust container RAM. - Include a Clear Disclaimer for Decision-Support Tools: Especially in healthcare or financial risk demos, state clearly that predictions are decision-support aids rather than final clinical or underwriting determinations.
Conclusion
Learning how to deploy a machine learning model using Streamlit bridges the gap between theoretical data science and interactive software delivery. With leak-free scikit-learn pipelines, @st.cache_resource, form-based input validation, and Docker containerisation, you can ship clean, reliable ML applications quickly.
Explore our live Software Development services, inspect our ML project portfolio, or contact Dick Madueke Chukwu for custom machine learning training or application engineering.
Madueke D. Chukwu (RiteClick)
Technology consultant, AI systems architect, and lead educator. Assisting fast-growing enterprises, engineering teams, and ambitious builders in implementing reliable infrastructure and intelligent automation.