Skip to main content

MLflow Tutorial for Machine Learning in Python — Part 9: Serve a Model as a REST API and in Docker

· 33 min read
Jagdish Kumawat
Founder @ Dewiride

Part 8 named the best shopper model the champion, but only programs that load MLflow and the model themselves could use it. In this part you'll turn the champion into a web service, a REST API that any program can send shopping sessions to and get purchase probabilities back from, first with mlflow models serve on your computer and then in a Docker container. You'll also add a call-api command to the project, the kind of client another team's program would be.

This is Part 9 of a 10-part series.

  1. Part 1: Install MLflow and Track Your First Experiment
  2. Part 2: Log Metrics Over Time and System Metrics
  3. Part 3: Log Artifacts and Datasets
  4. Part 4: Search and Filter Runs
  5. Part 5: Autologging and Hyperparameter Tuning with Nested Runs
  6. Part 6: Log, Load and Validate Models
  7. Part 7: Evaluate Models and Set Quality Gates
  8. Part 8: Register, Version and Promote Models with the Model Registry
  9. Part 9: Serve a Model as a REST API and in Docker (you are here)
  10. Part 10: Production Checklist and Recap (coming soon)

Every command and output on this page is real, captured while building the project.

What You'll Build in This Part​

  • the champion served as a REST API on your computer, with mlflow models serve;
  • requests in JSON and CSV, and what the server answers when a request doesn't fit the model;
  • a call-api command that sends a CSV file of sessions to the server and prints each one's purchase probability, with clear messages when the server refuses or isn't running;
  • a Docker image of the champion, built with mlflow models build-docker, and a container that answers call-api the same way.

What Model Serving Is​

Until now, scoring sessions meant loading the model in Python, with MLflow, scikit-learn and the right package versions installed. Serving turns that around: the model runs in a model server, and other programs send it data over HTTP, the language of the web, and get predictions back. They need nothing but the server's address.

MLflow's server, the inference server, has four endpoints. MLflow's guide to deploying a model as a local inference server lists them:

  • /invocations: "An inference endpoint that accepts POST requests with input data and returns predictions."
  • /ping: "Used for health checks."
  • /health: "Same as /ping".
  • /version: "Returns the MLflow version."

A request is the data in one of the server's layouts, such as dataframe_split: the column names once, then one list of values per row. The answer is JSON, {"predictions": [...]}, with one prediction per row. The server checks each request against the model's signature from Part 6 before the model sees it.

The same server can run in two places, which is what this part builds:

mlflow models serve runs it on your computer, in an environment MLflow builds from the model's own package versions. mlflow models build-docker puts it in an image, with Python, MLflow, the model and its packages, so any computer with Docker can run it.

The Example Project​

The shopper project predicts whether an online shopping session ends in a purchase. After Part 8, its registered model shopper-purchase-prediction has three versions, and champion points to version 2, the model trained with balanced class weights. The project's examples folder holds three sessions, in sessions.csv and in sessions.json: a likely buyer and two likely leavers. Part 8 scored them with version 2 as 0.8931, 0.0009 and 0.0033, and the server should give the same answers.

What This Part Costs​

Nothing for mlflow models serve. For the Docker steps, Docker Desktop is free under Docker's licence terms for "Small businesses (fewer than 250 employees AND less than $10 million in annual revenue)", personal use, education and non-commercial open source projects; it "requires a paid subscription" for professional use in larger organizations and for government entities. The image takes 1.31 GB of disk space.

Prerequisites​

  • Part 8 finished: the mlflow-server folder and its tracking server, and the dewiride-shopper-purchase-prediction project with the champion alias on version 2, from Part 8.
  • Docker Desktop, installed, for Steps 12 to 16.

Step 1: Start the Tracking Server​

Open a terminal in the mlflow-server folder and start the server, as before:

Terminal 1 (in mlflow-server)
uv run mlflow server --port 8080

Wait for Application startup complete and leave it running. The model server finds the champion through it.

Step 2: Serve the Champion​

Open a second terminal in the dewiride-shopper-purchase-prediction folder. Tell MLflow where the tracking server is, and serve the champion on port 5001:

Terminal 2
export MLFLOW_TRACKING_URI=http://127.0.0.1:8080
uv run mlflow models serve -m "models:/shopper-purchase-prediction@champion" -p 5001 --env-manager uv
  • -m "models:/shopper-purchase-prediction@champion": serve the version the alias points to. MLflow looks the alias up once, when the server starts.
  • -p 5001: the port. The default, 5000, is also used by AirPlay Receiver on a Mac.
  • --env-manager uv: build the model's environment with uv. Without it, MLflow uses virtualenv, which needs pyenv: Fixed: "MlflowException: Could not find the pyenv binary".
Output (excerpt)
2026/11/26 04:23:26 INFO mlflow.models.flavor_backend_registry: Selected backend for flavor 'python_function'
2026/11/26 04:23:26 INFO mlflow.utils.virtualenv: Creating a new environment in /Users/you/.mlflow/envs/mlflow-217dc732b07a188e27ddccb998d5ceea5443dbf8 with python version 3.15.2 using uv
...
Installed 89 packages in 709ms
...
2026/11/26 04:23:28 INFO mlflow.utils.environment: === Running command '['bash', '-c', 'source /Users/you/.mlflow/envs/mlflow-217dc732b07a188e27ddccb998d5ceea5443dbf8/bin/activate && exec uvicorn --host 127.0.0.1 --port 5001 --workers 1 mlflow.pyfunc.scoring_server.app:app']'
INFO: Started server process [61971]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:5001 (Press CTRL+C to quit)

The model server's output in a terminal: MLflow creating a new environment with Python 3.15.2 using uv, installing 89 packages, starting uvicorn on 127.0.0.1 port 5001, and Uvicorn running on http://127.0.0.1:5001.

  • Creating a new environment in .../.mlflow/envs/...: MLflow built an environment in your home folder with the champion's Python version and its 89 packages, the exact versions saved with it in Part 7. The next start reuses it.
  • exec uvicorn --host 127.0.0.1 --port 5001 --workers 1 ...: the server program, uvicorn, on your own computer only, with one worker.
  • Uvicorn running on http://127.0.0.1:5001: it's ready. Leave this terminal running.

The first start took about a minute here: building the environment took two seconds, and Python loading its packages for the first time took the rest. How to Serve a Registered Model by Alias with mlflow models serve shows the same command with a smaller model, and what happens when the alias moves while the server runs.

Step 3: Check That the Server Is Up​

Open a third terminal in the project folder. /ping answers when the model is loaded:

Terminal 3
curl -i http://127.0.0.1:5001/ping
Output
HTTP/1.1 200 OK
date: Thu, 26 Nov 2026 04:24:48 GMT
server: uvicorn
content-length: 1
content-type: application/json

curl -i's output for /ping in a terminal: HTTP/1.1 200 OK from server uvicorn.

200 OK: the champion is loaded. -i makes curl show the status line, which is the answer here; the body is only a line break. /version tells you which MLflow runs the server:

Terminal 3
curl http://127.0.0.1:5001/version
Output
3.18.0

How to Check That an MLflow Model Server Is Running adds a loop that waits until a starting server is ready.

Step 4: Ask for Predictions​

examples/sessions.json from Part 8 holds the three sessions in the dataframe_split layout. Send it to /invocations:

Terminal 3
curl http://127.0.0.1:5001/invocations -H "Content-Type: application/json" --data @examples/sessions.json
Output
{"predictions": [[0.10694143736565398, 0.893058562634346], [0.999142902134051, 0.0008570978659490101], [0.9966742334522005, 0.0033257665477994395]]}

curl's output in a terminal: the predictions as three pairs of probabilities, the second number in each 0.893, 0.0009 and 0.0033.

  • -H "Content-Type: application/json": tells the server the body is JSON.
  • --data @examples/sessions.json: sends the file's contents; the @ means "read from this file". How to Send a File in a POST Request with curl explains it, and why PowerShell uses -InFile instead.

One pair per session, in the file's order: the chance of not buying, then of buying. The second numbers, 0.8931, 0.0009 and 0.0033 rounded, are version 2's scores from Part 8: the server runs the champion. How to Send a dataframe_split Request to an MLflow Model Server goes through the layout.

Step 5: Send the Sessions as CSV​

The server reads CSV too. Send examples/sessions.csv with Content-Type: text/csv, and --data-binary, which keeps its line breaks:

Terminal 3
curl http://127.0.0.1:5001/invocations -H "Content-Type: text/csv" --data-binary @examples/sessions.csv
Output
{"predictions": [[0.10694143736565398, 0.893058562634346], [0.999142902134051, 0.0008570978659490101], [0.9966742334522005, 0.0033257665477994395]]}

The same predictions. In Part 8, mlflow models predict refused this file, because its whole numbers didn't match the signature's decimals. The server reads a CSV body with the column types from the model's signature, so here they're fine.

Use text/csv, not the application/csv that MLflow's guide shows: the server answers that with 415 Unsupported Media Type, as Fixed: This predictor only supports the following content types ... Got 'application/csv' shows.

Step 6: See How the Server Refuses a Request​

Send one column of the model's 17:

Terminal 3
curl http://127.0.0.1:5001/invocations -H "Content-Type: application/json" --data '{"dataframe_split": {"columns": ["Administrative"], "data": [[3.0]]}}'
Output
{"error_code": "INVALID_PARAMETER_VALUE", "message": "Failed to predict data ' Administrative\n0 3.0'. \nError: Failed to enforce schema of data ' Administrative\n0 3.0' with schema '['Administrative': double (required), 'Administrative_Duration': double (required), 'Informational': double (required), 'Informational_Duration': double (required), 'ProductRelated': double (required), 'ProductRelated_Duration': double (required), 'BounceRates': double (required), 'ExitRates': double (required), 'PageValues': double (required), 'SpecialDay': double (required), 'Month': string (required), 'OperatingSystems': double (required), 'Browser': double (required), 'Region': double (required), 'TrafficType': double (required), 'VisitorType': string (required), 'Weekend': boolean (required)]'. Error: Model is missing inputs ['Administrative_Duration', 'Informational', 'Informational_Duration', 'ProductRelated', 'ProductRelated_Duration', 'BounceRates', 'ExitRates', 'PageValues', 'SpecialDay', 'Month', 'OperatingSystems', 'Browser', 'Region', 'TrafficType', 'VisitorType', 'Weekend'].", "sqlstate": "KAM01", "error_class": "SCHEMA_ENFORCEMENT_FAILED"}

The refused request's JSON in a terminal: error_code INVALID_PARAMETER_VALUE, the model's schema of 17 columns, and Model is missing inputs listing the 16 missing columns, error_class SCHEMA_ENFORCEMENT_FAILED.

The server checked the request against the champion's signature and refused it with HTTP status 400, before the model ran. The body says why: error_code is INVALID_PARAMETER_VALUE, and the message ends with the 16 columns that are missing. A program that calls the server should read that message instead of guessing: How to Read the Error an MLflow Model Server Returns goes through the other cases.

Step 7: Add the Server's Address to the Settings​

Now the project gets its own client, call-api, which another program could be. It needs the server's address. Add it to Settings in config.py, below registered_model_name:

src/shopper_purchase_prediction/config.py (new field)
serving_url: str = Field(
default="http://127.0.0.1:5001",
min_length=1,
description="The address of the model server that call-api sends sessions to.",
)

With the SHOPPER_ prefix from Part 6, its variable is SHOPPER_SERVING_URL. Add it to .env.example:

.env.example (new lines)
# The model server that `uv run call-api` sends sessions to: mlflow models serve, or the Docker container.
SHOPPER_SERVING_URL=http://127.0.0.1:5001

Your .env needs no change: the default is the server's address.

Step 8: Add requests to the Project​

call-api sends HTTP requests with requests, Python's most used HTTP library:

Terminal 3
uv add requests
Output
Resolved 95 packages in 44ms
Built shopper-purchase-prediction @ file:///Users/you/source/dewiride-shopper-purchase-prediction
Prepared 1 package in 16ms
Uninstalled 1 package in 1ms
Installed 1 package in 4ms
~ shopper-purchase-prediction==0.1.0 (from file:///Users/you/source/dewiride-shopper-purchase-prediction)

uv didn't download anything: requests was already installed, because MLflow and the packages it depends on use it. uv add recorded it in pyproject.toml as a dependency of the project itself, requests>=2.34.2, so the project keeps it even if MLflow ever stops needing it. The only change it installed was the project, rebuilt with its new dependency list.

Step 9: Write the call-api Command​

Create src/shopper_purchase_prediction/call_api.py. It starts like predict.py, with its options: the CSV file of sessions, and the server's address, which defaults to the setting from Step 7:

src/shopper_purchase_prediction/call_api.py (options)
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
"""Read the sessions file and the server's address from the command line."""
parser = argparse.ArgumentParser(
prog="call-api",
description="Score online shopping sessions with a model served by MLflow.",
)
parser.add_argument(
"--input", type=Path, required=True, help="CSV file of sessions, one per row"
)
parser.add_argument(
"--url",
default=None,
help="the model server's address, such as http://127.0.0.1:5001 "
"(default: SHOPPER_SERVING_URL)",
)
return parser.parse_args(argv)

Then the request. pandas reads the CSV, to_dict(orient="split", index=False) turns it into the dataframe_split layout of Step 4, and requests.post(..., json=payload) sends it as JSON:

src/shopper_purchase_prediction/call_api.py (the request)
url = (args.url or get_settings().serving_url).rstrip("/")

sessions = pd.read_csv(args.input)
# MLflow's dataframe_split layout: the column names once, then each session's values in the
# same order. The server turns every value into the type the model's signature asks for.
payload = {"dataframe_split": sessions.to_dict(orient="split", index=False)}
try:
response = requests.post(f"{url}/invocations", json=payload, timeout=TIMEOUT_SECONDS)
except requests.ConnectionError:
logger.error("Can't reach the model server at %s. Is it running?", url)
return 1
except requests.Timeout:
logger.error("The model server at %s didn't answer in %d seconds", url, TIMEOUT_SECONDS)
return 1
  • timeout=TIMEOUT_SECONDS: 30 seconds. Without a timeout, requests can wait forever for a server that's stuck; a few sessions take the model well under a second.
  • requests.ConnectionError: nothing answered at that address, so the command says so in one line and exits with 1, instead of a long traceback.
  • requests.Timeout: the server answered too slowly.

Then the answer. A refused request comes back with a status other than 200 and MLflow's explanation in message, as Step 6 showed:

src/shopper_purchase_prediction/call_api.py (the answer)
if response.status_code != 200:
# MLflow explains a refused request in the "message" field of a JSON body.
try:
reason = response.json()["message"]
except ValueError, KeyError:
reason = response.text
logger.error("The model server answered HTTP %d: %s", response.status_code, reason)
return 2

# One pair per session, in the file's order: (chance of not buying, chance of buying).
probabilities = response.json()["predictions"]
summary = pd.DataFrame(
{
"session": range(1, len(probabilities) + 1),
"purchase_probability": [round(pair[1], 4) for pair in probabilities],
}
)
print(summary.to_string(index=False))
return 0
  • except ValueError, KeyError:: if the body isn't JSON, or has no message, the command prints the body as text. Python 3.14 and later accept the two exception types without brackets, and Ruff writes them that way for this Python 3.15 project.
  • Exit codes: 0 for predictions, 1 when the server can't be reached or answers too slowly, and 2 when it refused the sessions, as predict uses 2 for sessions that don't fit the model, so a script can tell the cases apart.
  • The table: the same two columns predict prints, so the two commands can be compared side by side.

The complete file:

The complete call_api.py in a macOS-style code window: the options, the request with requests.post and a 30-second timeout, the ConnectionError and Timeout messages, the refused-request message and the table of purchase probabilities.

src/shopper_purchase_prediction/call_api.py
"""Score online shopping sessions from a CSV file with a model that MLflow serves as a REST API."""

import argparse
import logging
from collections.abc import Sequence
from pathlib import Path

import pandas as pd
import requests

from shopper_purchase_prediction.config import get_settings

logger = logging.getLogger("shopper_purchase_prediction")

# The model server scores a few sessions in well under a second. Longer than this means it's stuck.
TIMEOUT_SECONDS = 30


def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
"""Read the sessions file and the server's address from the command line."""
parser = argparse.ArgumentParser(
prog="call-api",
description="Score online shopping sessions with a model served by MLflow.",
)
parser.add_argument(
"--input", type=Path, required=True, help="CSV file of sessions, one per row"
)
parser.add_argument(
"--url",
default=None,
help="the model server's address, such as http://127.0.0.1:5001 "
"(default: SHOPPER_SERVING_URL)",
)
return parser.parse_args(argv)


def main(argv: Sequence[str] | None = None) -> int:
"""Send the sessions to the model server and print each one's purchase probability."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
datefmt="%Y/%m/%d %H:%M:%S",
)
args = parse_args(argv)
url = (args.url or get_settings().serving_url).rstrip("/")

sessions = pd.read_csv(args.input)
# MLflow's dataframe_split layout: the column names once, then each session's values in the
# same order. The server turns every value into the type the model's signature asks for.
payload = {"dataframe_split": sessions.to_dict(orient="split", index=False)}
try:
response = requests.post(f"{url}/invocations", json=payload, timeout=TIMEOUT_SECONDS)
except requests.ConnectionError:
logger.error("Can't reach the model server at %s. Is it running?", url)
return 1
except requests.Timeout:
logger.error("The model server at %s didn't answer in %d seconds", url, TIMEOUT_SECONDS)
return 1

if response.status_code != 200:
# MLflow explains a refused request in the "message" field of a JSON body.
try:
reason = response.json()["message"]
except ValueError, KeyError:
reason = response.text
logger.error("The model server answered HTTP %d: %s", response.status_code, reason)
return 2

# One pair per session, in the file's order: (chance of not buying, chance of buying).
probabilities = response.json()["predictions"]
summary = pd.DataFrame(
{
"session": range(1, len(probabilities) + 1),
"purchase_probability": [round(pair[1], 4) for pair in probabilities],
}
)
print(summary.to_string(index=False))
return 0

Last, make it a command. In pyproject.toml, add a line under [project.scripts]:

pyproject.toml (new line under [project.scripts])
call-api = "shopper_purchase_prediction.call_api:main"

Step 10: Score Through the API​

With the model server still running in Terminal 2:

Terminal 3
uv run call-api --input examples/sessions.csv
Output
Built shopper-purchase-prediction @ file:///Users/you/source/dewiride-shopper-purchase-prediction
Uninstalled 1 package in 0.99ms
Installed 1 package in 3ms
session purchase_probability
1 0.8931
2 0.0009
3 0.0033

call-api's output in a terminal: uv rebuilding the project, then the table of sessions 1 to 3 with purchase probabilities 0.8931, 0.0009 and 0.0033.

The same table predict printed in Part 8, but call-api loaded no model: it asked the server. uv rebuilt the project first because pyproject.toml has a new command.

Step 11: Stop the Model Server​

Go to Terminal 2 and press Ctrl+C:

Output
^CINFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [61971]

Run call-api again, with nothing listening:

Terminal 3
uv run call-api --input examples/sessions.csv
Output
2026/11/26 04:26:31 ERROR shopper_purchase_prediction: Can't reach the model server at http://127.0.0.1:5001. Is it running?

call-api's output in a terminal with the server stopped: ERROR shopper_purchase_prediction: Can't reach the model server at http://127.0.0.1:5001. Is it running?

One clear line and exit code 1, from the requests.ConnectionError branch of Step 9. Next, the same server in a Docker container, on the same address.

Step 12: Check That Docker Is Running​

Start Docker Desktop, then check that its engine answers:

Terminal 3
docker version
Output (excerpt)
Client:
Version: 29.9.3
...
Server: Docker Desktop 4.100.1 (247138)
Engine:
Version: 29.9.3
...
OS/Arch: linux/arm64

A Server section means the engine is running. If it says Cannot connect to the Docker daemon, Docker Desktop isn't running yet: Fixed: Cannot connect to the Docker daemon. The engine here runs linux/arm64, an Apple silicon Mac; that matters in Step 14.

Step 13: Build a Docker Image of the Champion​

Terminal 3
export MLFLOW_TRACKING_URI=http://127.0.0.1:8080
uv run mlflow models build-docker -m "models:/shopper-purchase-prediction@champion" -n shopper-purchase-prediction:2 --env-manager local
  • -n shopper-purchase-prediction:2: the image's name, with the tag 2, the version the alias points to now. MLflow resolves @champion once, while it builds, so the image holds version 2 for good; naming it after the version says so.
  • --env-manager local: install the model's packages into the image's own Python. Not uv here: the code that builds the image accepts only local, conda and virtualenv, and fails minutes in with uv: Fixed: Invalid value for env_manager: uv.

The first line points this terminal at the tracking server, as Step 2 did for Terminal 2: MLflow downloads the champion from it while it builds.

Output (excerpt)
2026/11/26 04:27:15 INFO mlflow.pyfunc.backend: Building docker image with name shopper-purchase-prediction:2
[+] Building 165.7s (14/14) FINISHED
=> [1/9] FROM docker.io/library/python:3.15.2-slim@sha256:63bb298d2b7b88f176f51b5189f54ce6535c997682ea70885d2132f5d473a8a5
=> [2/9] RUN printf '%s\n' 'Acquire::http::Timeout "30";' 'Acquire::https::Timeout "30";' 'Acquire::Retries "3";' > /etc/apt/apt.conf.d/99-mlflow-timeouts
=> [3/9] RUN apt-get -y update && apt-get install -y --no-install-recommends nginx
=> [4/9] WORKDIR /opt/mlflow
=> [5/9] RUN pip install mlflow==3.18.0
=> [6/9] COPY model_dir /opt/ml/model
=> [7/9] RUN python -c "from mlflow.models import container as C; C._install_pyfunc_deps('/opt/ml/model', install_mlflow=False, env_manager='local');"
=> [8/9] RUN chmod o+rwX /opt/mlflow/
=> [9/9] RUN rm -rf /var/lib/apt/lists/*
=> => naming to docker.io/library/shopper-purchase-prediction:2

The image build in a terminal: Building docker image with name shopper-purchase-prediction:2, the nine steps from FROM python:3.15.2-slim through installing nginx, MLflow 3.18.0 and the model's packages, and naming to docker.io/library/shopper-purchase-prediction:2.

MLflow downloaded the champion from the tracking server, wrote a Dockerfile and built it, in a bit over three minutes on this first build. The image starts from Python 3.15.2, the model's own version, adds nginx and MLflow 3.18.0, copies the model in and installs its packages; installing MLflow was the longest step, 103 seconds. How to Build a Docker Image for an MLflow Model goes through each step, and How to Generate a Dockerfile for an MLflow Model shows the Dockerfile itself.

Check the image:

Terminal 3
docker images shopper-purchase-prediction
Output
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
shopper-purchase-prediction:2 cba1dca42ecb 1.31GB 0B

1.31 GB, most of it Python packages: MLflow and what the model needs.

Step 14: Run the Champion in a Container​

Terminal 3
docker run -d --name shopper-api --platform linux/amd64 -e MLFLOW_MODELS_WORKERS=2 -p 127.0.0.1:5001:8080 shopper-purchase-prediction:2
Output
d898d7728b88c06f96d85c19bb9649b97044225b1c47cedfe334df31ce203505

The same command works in PowerShell. Each option:

The container needs a few seconds to start: until its model server is up, /ping answers 502 Bad Gateway. Then:

Terminal 3
curl -i http://127.0.0.1:5001/ping
Output
HTTP/1.1 200 OK
Server: nginx/1.26.3
Date: Thu, 26 Nov 2026 04:31:04 GMT
Content-Type: application/json
Content-Length: 1
Connection: keep-alive

Two outputs in a terminal: docker images listing shopper-purchase-prediction:2 at 1.31GB, and curl -i's HTTP/1.1 200 OK from Server nginx/1.26.3 for the container's /ping.

Server: nginx/1.26.3, not uvicorn: in the container, nginx takes the requests on port 8080 and passes them to the model server. It passes on only /ping and /invocations; /health and /version get 404 there: Fixed: An MLflow Model Container Answers 404 for /health and /version.

Step 15: Score Through the Container​

call-api doesn't know or care what's behind the address:

Terminal 3
uv run call-api --input examples/sessions.csv
Output
session purchase_probability
1 0.8931
2 0.0009
3 0.0033

call-api's output in a terminal, through the Docker container: sessions 1 to 3 with purchase probabilities 0.8931, 0.0009 and 0.0033.

The same probabilities, from the container this time. Its log shows both programs at work:

Terminal 3
docker logs shopper-api
Output (excerpt)
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started parent process [21]
2026/11/26 04:30:58 [error] 22#22: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.17.0.1, server: , request: "GET /ping HTTP/1.1", upstream: "http://127.0.0.1:8000/ping", host: "127.0.0.1:5001"
172.17.0.1 - - [26/Nov/2026:04:30:58 +0000] "GET /ping HTTP/1.1" 502 157 "-" "curl/8.7.1"
...
INFO: Started server process [24]
INFO: Waiting for application startup.
INFO: Started server process [25]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Application startup complete.
...
INFO: 172.17.0.1:0 - "POST /invocations HTTP/1.0" 200 OK
172.17.0.1 - - [26/Nov/2026:04:31:06 +0000] "POST /invocations HTTP/1.1" 200 148 "-" "python-requests/2.34.2"

docker logs' output in a terminal: uvicorn running on 127.0.0.1:8000 inside the container, nginx's 502 for an early /ping while the workers start, two worker processes starting, and 200 lines for call-api's POST /invocations.

  • Uvicorn running on http://127.0.0.1:8000: the model server, on port 8000 inside the container, behind nginx.
  • The 502 lines: early /ping requests, while the workers were still loading the model.
  • Two Started server process lines: the two workers of MLFLOW_MODELS_WORKERS=2.
  • The last two lines: call-api's request, python-requests/2.34.2, as the model server and nginx each logged it.

Step 16: Stop and Remove the Container​

Terminal 3
docker stop shopper-api
docker rm shopper-api
Output
shopper-api
shopper-api

docker stop shut the container down, and docker rm deleted it. The image stays, so docker run can start it again at any time, without the tracking server: the model is inside it. How to Stop and Remove a Docker Container has the details.

Step 17: Save Your Work with Git​

In the project terminal:

Terminal 3
git status --short --untracked-files=all
Output
M .env.example
M pyproject.toml
M src/shopper_purchase_prediction/config.py
M uv.lock
?? src/shopper_purchase_prediction/call_api.py
Terminal 3
git add .
git commit -m "Score sessions through the champion's REST API with call-api"
Output
[master 3153d99] Score sessions through the champion's REST API with call-api
5 files changed, 89 insertions(+)
create mode 100644 src/shopper_purchase_prediction/call_api.py

git's output in a terminal: four modified files and the new call_api.py in git status, then the commit Score sessions through the champion's REST API with call-api, 5 files changed, 89 insertions.

Your Folders Now Look Like This​

source/
source/
├── mlflow-server/
│ ├── .venv/
│ ├── mlartifacts/
│ ├── mlflow.db
│ ├── pyproject.toml
│ └── uv.lock
├── dewiride-house-price-prediction/
│ └── ...
├── dewiride-term-deposit-prediction/
│ └── ...
└── dewiride-shopper-purchase-prediction/
├── .venv/
├── data/
│ └── online-shoppers.zip
├── examples/
│ ├── sessions.csv
│ └── sessions.json
├── src/
│ └── shopper_purchase_prediction/
│ ├── __init__.py
│ ├── call_api.py
│ ├── config.py
│ ├── data.py
│ ├── evaluate.py
│ ├── model.py
│ ├── predict.py
│ ├── promote.py
│ ├── registry.py
│ ├── train.py
│ └── validate.py
├── .env
├── .env.example
├── .gitignore
├── .python-version
├── README.md
├── pyproject.toml
└── uv.lock

Two things live outside these folders now: the champion's environment, in .mlflow/envs in your home folder, which mlflow models serve reuses, and the image shopper-purchase-prediction:2, in Docker.

Stop the Server When You're Done​

Go to the first terminal and press Ctrl+C. Your runs, models and the registry stay in mlflow.db and mlartifacts/.

Keep the folders and the image for Part 10. To free the space later: docker rmi shopper-purchase-prediction:2 removes the image (How to Remove a Docker Image), and deleting the folder .mlflow/envs in your home folder, with no model server running, removes the environments MLflow built; the next mlflow models serve builds one again. To remove everything the series created, stop the server first, then delete the mlflow-server folder, the three project folders and the scikit_learn_data folder in your home folder as well.

Common Mistakes​

MistakeWhat happensDo this instead
mlflow models serve without --env-managerMlflowException: Could not find the pyenv binary, without pyenv--env-manager uv
The default port, 5000, on a Maclocalhost:5000 reaches AirPlay Receiver, which answers 403 Forbidden-p 5001, and 127.0.0.1
Content-Type: application/csv, as in MLflow's guide415 Unsupported Media Typetext/csv
--env-manager uv for build-dockerThe build fails at step 7--env-manager local
Moving @champion and expecting a running server or an image to followBoth keep the version they loaded or were built withRestart the server; build a new image
docker run -p 5001:8080 without 127.0.0.1The model is reachable from your whole network-p 127.0.0.1:5001:8080

Troubleshooting​

SymptomLikely causeFix
Can't reach the model server at http://127.0.0.1:5001. Is it running?No server, or a container that's still startingStart one, and wait for /ping
curl: (52) Empty reply from server right after docker runThe container hasn't started listening yetWait a few seconds
502 Bad Gateway from the containernginx is up, the model server isn't yetWait until /ping answers 200
docker run fails with ports are not available: exposing port TCP 127.0.0.1:5001 ... bind: address already in useSomething else, such as mlflow models serve, still listens on 5001Stop it with Ctrl+C, then docker rm shopper-api and run again
The model server answered HTTP 400: ... from call-apiThe CSV file doesn't match the model's signatureRead the end of the message, and fix the file
The container uses a lot of memoryOne worker per CPU-e MLFLOW_MODELS_WORKERS=2

FAQ​

Is the model server safe to put on the internet?​

Not as it is: it has no sign-in, so anyone who can reach it can use it, and some error answers include the server's file paths. MLflow's reference warns that --host 0.0.0.0 "is NOT a security setting". Keep it on 127.0.0.1, or behind something that checks who's calling. Part 10 comes back to this.

How do I release a new champion?​

Move the alias with promote (Part 8), then restart mlflow models serve, or build and run a new image, tagged with the new version.

Why does the server's answer have two numbers per session?​

The champion was logged to return predict_proba's two probabilities, not buying and buying (Part 6). call-api keeps the second.

Can I send many sessions at once?​

Yes: one request with many rows is one call, and the predictions come back in the same order.

Conclusion​

The champion now runs as a REST API. mlflow models serve -m "models:/shopper-purchase-prediction@champion" -p 5001 --env-manager uv served it with its own packages, answered /ping and /version, gave version 2's probabilities for the sessions in JSON and in CSV, and refused a one-column request with 400 and a reason. The new call-api command sent the CSV file as dataframe_split and printed 0.8931, 0.0009 and 0.0033, with one-line messages when the server was down. mlflow models build-docker packaged the champion as shopper-purchase-prediction:2, and a container of it on 127.0.0.1:5001 gave call-api the same answers.

In Part 10 you'll go through what the series built with a production checklist, and recap every part.

Additional Resources​


← Previous: Part 8: Register, Version and Promote Models with the Model Registry

Next → Part 10: Production Checklist and Recap (coming soon)