My first MLflow tracking server answered on port 5000, passed its own health check and then refused every request nginx sent it with a 403. Nothing in the old MLflow 2 tutorials I had bookmarked mentioned host header validation, because it didn’t exist when they were written. MLflow 3 also starts a background job runner that ate 2.6 GiB of RAM on a 4 GB VM, and its default sklearn format refused to save one of my two models.
So I built the whole stack twice. It is an MLflow tracking server and model registry on PostgreSQL, artifacts in a self-hosted S3 bucket, and nginx with a Let’s Encrypt certificate and basic auth in front. On top of that I logged a real German Credit model, registered it and promoted it with aliases. The lab ran in November 2026 on two e2-medium VMs, box1 on Ubuntu 26.04.1 LTS and box2 on Ubuntu 24.04.5 LTS, both on MLflow 3.18.0, and every prompt, error and number below comes from those two boxes.
What the finished server looks like
Only nginx listens on the network. The MLflow server binds to 127.0.0.1:5000, PostgreSQL holds runs, metrics and the registry, and an S3 bucket holds the model files. Because the server runs with --serve-artifacts, clients upload artifacts through MLflow itself, so a data scientist’s laptop never needs S3 credentials. The red box is where boto3 went the one time I forgot the S3 endpoint variable.

For the S3 side I used Garage in a Docker container instead of MinIO. The MinIO community repository was archived in April 2026 (the minio/minio repo is read-only), so I did not want to start a new server on it. Garage speaks the S3 API, runs as one binary, and is AGPL licensed. If you already pay for AWS S3, Cloudflare R2 or another S3 service, skip the Garage section. Put that service’s key, secret and region in the environment file, set --artifacts-destination to your bucket, and keep MLFLOW_S3_ENDPOINT_URL only for non-AWS services (on AWS S3 itself, delete that line).
Prerequisites and sizing
You need an Ubuntu 26.04 or 24.04 server with sudo, a DNS name pointing at it, and ports 80 and 443 open. My lab VMs sat behind a cloud firewall that allowed only 22, 80 and 443, and that was the whole firewall story. The numbers below are what the two boxes actually used, so treat them as the floor:
- Lab floor: 2 vCPU, 4 GB RAM, 30 GB disk (e2-medium)
- MLflow with job execution on: 2.6 GiB in the unit’s cgroup, the VM down to 190 MB free
- MLflow with job execution off: about 740 MiB on 26.04, 690 MiB on 24.04
- PostgreSQL after two runs and two model versions: a 154 KB dump
- Artifacts: 173 KB for the logistic regression model, 2 MB for the gradient boosting one
What grows in production is the artifact bucket, not the database. Metrics and params are tiny rows, but every logged model, dataset sample and plot lands in S3, and a team that logs a model per training run fills tens of gigabytes a month. Size the disk (or the bucket) for that, give the VM 8 GB if more than a handful of people hit the UI, and keep the database on the same box until its dump stops fitting in a coffee break.
Set the values that repeat through the guide once. Use your own DNS name and two strong passwords; the admin password must be at least 12 characters or MLflow refuses to start:
export MLFLOW_FQDN="mlflow.example.com"
export MLFLOW_DB_PASS="ChangeThisDbPass2026"
export MLFLOW_ADMIN_PASS="ChangeThisAdminPass2026"
export LE_EMAIL="[email protected]"
Install PostgreSQL, nginx, certbot, Docker and pipx from the Ubuntu archive. Both releases ship all five, so no extra repositories are needed.
sudo apt-get update
sudo apt-get install -y postgresql nginx certbot python3-certbot-nginx docker.io pipx
On 26.04 that pulled PostgreSQL 18, nginx 1.28, certbot 4.0 and Docker 29.1; on 24.04 it was PostgreSQL 16, nginx 1.24 and certbot 2.9. MLflow did not care about any of those differences. If you’d rather run PostgreSQL from the upstream PGDG repository, our PostgreSQL 18 on Ubuntu 26.04 notes cover that setup.
Creating the PostgreSQL databases
MLflow needs two databases: mlflow for experiments, runs and the registry, and mlflow_auth for basic auth users and permissions. Keeping them apart means you can restore one without clobbering the other. Create one role that owns both:
sudo -u postgres psql -c "CREATE ROLE mlflow WITH LOGIN PASSWORD '${MLFLOW_DB_PASS}';"
sudo -u postgres psql -c "CREATE DATABASE mlflow OWNER mlflow;"
sudo -u postgres psql -c "CREATE DATABASE mlflow_auth OWNER mlflow;"
Before going further, log in over TCP exactly the way MLflow will, with the password and 127.0.0.1, because that’s the path that fails when pg_hba.conf has been changed:
psql "postgresql://mlflow:${MLFLOW_DB_PASS}@127.0.0.1:5432/mlflow" -c '\conninfo'
On 24.04 with PostgreSQL 16 the answer is two lines, and the SSL line tells you the stock Ubuntu snakeoil certificate is already encrypting local connections. PostgreSQL 18 on 26.04 prints the same facts as a table instead:
You are connected to database "mlflow" as user "mlflow" on host "127.0.0.1" at port "5432".
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
If psql asks for a password and then says authentication failed, the role password didn’t match what you exported. Fix it with ALTER ROLE now, since MLflow’s error for the same problem is buried in a long Python traceback.
Running Garage as the S3 artifact store
Garage needs a small TOML file with an RPC secret and an admin token. I kept the S3 and admin ports on 127.0.0.1 only, because nothing outside the VM should talk to the bucket directly. Create the directories and open the config:
sudo mkdir -p /etc/garage /var/lib/garage/meta /var/lib/garage/data
sudo vim /etc/garage/garage.toml
Paste the config with the two placeholders left as they are; the next command fills them with random values.
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "sqlite"
replication_factor = 1
rpc_bind_addr = "[::]:3901"
rpc_public_addr = "127.0.0.1:3901"
rpc_secret = "RPC_SECRET"
[s3_api]
s3_region = "garage"
api_bind_addr = "[::]:3900"
[admin]
api_bind_addr = "[::]:3903"
admin_token = "ADMIN_TOKEN"
Fill the secrets, lock the file down and start the container. The image tag is pinned on purpose, since a Garage major version can change the metadata format:
sudo sed -i "s/RPC_SECRET/$(openssl rand -hex 32)/; s/ADMIN_TOKEN/$(openssl rand -base64 32 | tr -d '=+/')/" /etc/garage/garage.toml
sudo chmod 600 /etc/garage/garage.toml
export GARAGE_TAG="v2.5.0" # https://git.deuxfleurs.fr/Deuxfleurs/garage/releases/tag/v2.5.0
sudo docker run -d --name garage --restart unless-stopped \
-p 127.0.0.1:3900:3900 -p 127.0.0.1:3903:3903 \
-v /etc/garage/garage.toml:/etc/garage.toml:ro \
-v /var/lib/garage/meta:/var/lib/garage/meta \
-v /var/lib/garage/data:/var/lib/garage/data \
dxflrs/garage:${GARAGE_TAG} /garage server --single-node
The --single-node flag assigns the cluster layout for you, which used to be three separate commands. Now create the bucket, a key for MLflow, and give that key read, write and owner rights on the bucket:
sudo docker exec garage /garage bucket create mlflow-artifacts
sudo docker exec garage /garage key create mlflow-server
sudo docker exec garage /garage bucket allow --read --write --owner mlflow-artifacts --key mlflow-server
sudo docker exec garage /garage bucket info mlflow-artifacts
The last command should end with the key listed under the bucket with RWO. If that table is empty, the bucket allow step did not run and every upload will come back as AccessDenied:
Global alias: mlflow-artifacts
==== KEYS FOR THIS BUCKET ====
Permissions Access key Local aliases
RWO GKxxxxxxxxxxxxxxxxxxxxxxxx mlflow-server
Garage prints its own INFO log lines on every exec. Add -e RUST_LOG=warn after docker exec when you want clean output, as the next section does when it reads the key back.
Installing MLflow into a uv virtual environment
I did not want MLflow’s 96 dependencies anywhere near the system Python, so it lives in /opt/mlflow, built with uv. Ubuntu has no uv package, but pipx does, and installing it with a global home puts uv in /usr/local/bin on both releases. The --global flag doesn’t exist in the pipx that 24.04 ships, which is why the two environment variables do the job instead:
sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install uv
sudo useradd --system --home-dir /var/lib/mlflow --create-home --shell /usr/sbin/nologin mlflow
sudo uv venv /opt/mlflow --python /usr/bin/python3
sudo uv pip install --python /opt/mlflow/bin/python "mlflow[auth]==3.18.0" "psycopg[binary]" boto3 # https://github.com/mlflow/mlflow/releases/tag/v3.18.0
My first attempt (with the wrong driver, see below) resolved 96 packages in under 8 seconds on 26.04, and swapping in psycopg 3 afterwards added two more packages in a fraction of a second. That speed still surprises me after years of pip. Confirm the version the service will run:
/opt/mlflow/bin/mlflow --version
Does the venv binary report the version you pinned? It should.
mlflow, version 3.18.0
A clean version string only proves the package imports. The database driver is loaded later, when the server first opens the backend store, which is exactly where my first attempt broke.
Error initializing backend store: No module named ‘psycopg’
My first install used psycopg2-binary, the driver every MLflow tutorial I’d read recommends, and the service died on start. It turned out SQLAlchemy 2.1 changed what a plain postgresql:// URL means: the SQLAlchemy 2.1 migration notes list “Default PostgreSQL driver changed to psycopg (psycopg 3)”, and MLflow 3.18 pulls in SQLAlchemy 2.1.8. This is what the journal showed:

Installing psycopg[binary], as in the command above, fixes it with no change to the URL. You could keep psycopg2 and write postgresql+psycopg2:// instead, but I’d rather follow the library’s new default than fight it on every upgrade.
Writing the environment file and the systemd unit
All secrets go into one environment file readable by root and the mlflow group, and nothing secret goes on the command line. I learned that the hard way: my first unit passed --backend-store-uri ${MLFLOW_BACKEND_STORE_URI} in ExecStart, and systemctl status then printed the database password in clear text to anyone who could run it. MLflow reads MLFLOW_BACKEND_STORE_URI from the environment by itself, so the flag isn’t needed at all. Create the directory and the file:
sudo mkdir -p /etc/mlflow
sudo vim /etc/mlflow/mlflow.env
Paste the template exactly as shown. The uppercase placeholders get replaced in the next step.
MLFLOW_BACKEND_STORE_URI=postgresql://mlflow:[email protected]:5432/mlflow
MLFLOW_S3_ENDPOINT_URL=http://127.0.0.1:3900
AWS_ACCESS_KEY_ID=GARAGE_KEY_ID
AWS_SECRET_ACCESS_KEY=GARAGE_SECRET
AWS_DEFAULT_REGION=garage
MLFLOW_AUTH_CONFIG_PATH=/etc/mlflow/basic_auth.ini
MLFLOW_FLASK_SERVER_SECRET_KEY=FLASK_SECRET
MLFLOW_SERVER_ENABLE_JOB_EXECUTION=false
Two lines in there carry the lessons from my lab. MLFLOW_SERVER_ENABLE_JOB_EXECUTION=false stops the huey job runner that MLflow 3.18 starts by default for its GenAI features; with it on, the unit sat at 2.6 GiB and the 4 GB VM had 190 MB free. With it off, the same server used about 740 MiB. If you use MLflow for LLM evaluation jobs, leave it on and buy the RAM. The admin password gets its own line in a moment, because MLflow ships no default admin password any more and will not start basic auth without one.
The basic auth plugin has its own config file. Point its user database at the second PostgreSQL database instead of the default SQLite file in the working directory:
sudo vim /etc/mlflow/basic_auth.ini
With default_permission = READ, every logged-in user can see every experiment but only edit their own.
[mlflow]
default_permission = READ
database_uri = postgresql://mlflow:[email protected]:5432/mlflow_auth
admin_username = admin
authorization_function = mlflow.server.auth:authenticate_request_basic_auth
grant_default_workspace_access = false
Now read the Garage key back, fill the placeholders in both files with sed, and append the admin password as its own line. Stick to letters, digits and hyphens in the two passwords: a /, &, @ or : breaks either the sed or the postgresql:// URL. The Garage key and secret stay in shell variables, so they never land in your history.
KEYID=$(sudo docker exec -e RUST_LOG=warn garage /garage key info mlflow-server | awk '/^Key ID/{print $3}')
SECRET=$(sudo docker exec -e RUST_LOG=warn garage /garage key info mlflow-server --show-secret | awk '/^Secret key/{print $3}')
sudo sed -i "s/DB_PASSWORD/${MLFLOW_DB_PASS}/; s/GARAGE_KEY_ID/$KEYID/; s/GARAGE_SECRET/$SECRET/; s/FLASK_SECRET/$(openssl rand -hex 32)/" /etc/mlflow/mlflow.env
echo "MLFLOW_AUTH_ADMIN_PASSWORD=${MLFLOW_ADMIN_PASS}" | sudo tee -a /etc/mlflow/mlflow.env >/dev/null
sudo sed -i "s/DB_PASSWORD/${MLFLOW_DB_PASS}/" /etc/mlflow/basic_auth.ini
sudo chown root:mlflow /etc/mlflow/mlflow.env /etc/mlflow/basic_auth.ini
sudo chmod 640 /etc/mlflow/mlflow.env /etc/mlflow/basic_auth.ini
Each of those lines ran on the lab VMs, but I fixed the order after the runs (the admin password used to be a placeholder in the template) and did not replay the whole sequence on a fresh VM. So look before you start anything: sudo grep -cE 'DB_PASSWORD|GARAGE_KEY_ID|GARAGE_SECRET|FLASK_SECRET' /etc/mlflow/mlflow.env /etc/mlflow/basic_auth.ini should print 0 for both files, sudo grep -E '=$|:@' /etc/mlflow/mlflow.env /etc/mlflow/basic_auth.ini should print nothing (an empty shell variable leaves a blank value behind), and sudo tail -1 /etc/mlflow/mlflow.env should show the admin password line. Next comes the unit file itself.
sudo vim /etc/systemd/system/mlflow.service
Replace mlflow.example.com in the two flags with your own name. Both have to match the hostname people type, and the CORS one needs the https:// scheme:
[Unit]
Description=MLflow tracking server
After=network-online.target postgresql.service docker.service
Wants=network-online.target
[Service]
User=mlflow
Group=mlflow
WorkingDirectory=/var/lib/mlflow
EnvironmentFile=/etc/mlflow/mlflow.env
ExecStart=/opt/mlflow/bin/mlflow server \
--artifacts-destination s3://mlflow-artifacts \
--serve-artifacts \
--host 127.0.0.1 --port 5000 \
--workers 2 \
--allowed-hosts mlflow.example.com \
--cors-allowed-origins https://mlflow.example.com \
--app-name basic-auth
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Start it and give it a minute. The first start runs every database migration (71 tables on a fresh database) and took about 60 seconds on both boxes, so a status check straight away shows activating and looks like a hang:
sudo systemctl daemon-reload
sudo systemctl enable --now mlflow
systemctl status mlflow --no-pager | head -7
A healthy server shows active (running) with around 16 tasks and memory well under a gigabyte. If you see 50-plus tasks and 1.4 GB or more, the job execution line didn’t make it into the environment file:
● mlflow.service - MLflow tracking server
Loaded: loaded (/etc/systemd/system/mlflow.service; enabled; preset: enabled)
Active: active (running) since Thu 2026-11-12 11:36:33 UTC; 35s ago
Invocation: e71ecfa600534efca134b738bd7afa8c
Main PID: 10125 (mlflow)
Tasks: 16 (limit: 3915)
Memory: 740.8M (peak: 740.8M)
If the unit flaps between activating and failed, read sudo journalctl -u mlflow -n 40. The three causes I hit were the psycopg driver above, a wrong database password, and the missing admin password covered in the troubleshooting section.
Putting nginx and HTTPS in front
nginx terminates TLS and passes everything to 127.0.0.1:5000. Two settings matter for MLflow specifically: a large client_max_body_size because model uploads go through this proxy, and proxy_request_buffering off so nginx streams a 2 GB artifact instead of spooling it to disk first. Open a new site file:
sudo vim /etc/nginx/sites-available/mlflow
Add the server block, with your name in server_name.
server {
listen 80;
listen [::]:80;
server_name mlflow.example.com;
client_max_body_size 2G;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
proxy_request_buffering off;
}
}
Enable it, drop the default site, test and reload, then let certbot add the certificate and the HTTP to HTTPS redirect. The nginx and Let’s Encrypt guide for Ubuntu 26.04 explains renewals and the DNS-01 route if port 80 can’t be opened:
sudo ln -sf /etc/nginx/sites-available/mlflow /etc/nginx/sites-enabled/mlflow
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d "${MLFLOW_FQDN}" -m "${LE_EMAIL}" --agree-tos --redirect --non-interactive
Certbot edits the site file in place and confirms both the certificate and the deploy.
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/mlflow.example.com/fullchain.pem
Key is saved at: /etc/letsencrypt/live/mlflow.example.com/privkey.pem
This certificate expires on 2027-02-10.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.
Deploying certificate
Successfully deployed certificate for mlflow.example.com to /etc/nginx/sites-enabled/mlflow
Congratulations! You have successfully enabled HTTPS on https://mlflow.example.com
Something I didn’t expect: two minutes after nginx logged its first request, scanners started asking for /.env, /.git/config and two dozen variants of them. The hostname was brand new, so my best guess is they read it from the public Certificate Transparency logs. The nginx log held 27 .env probes in under a quarter of an hour; they got 403 from the Host check, 502 while I restarted MLflow, and 401 once basic auth was on. None got a file. That’s the practical argument for turning auth on before you request the certificate, which is why the unit above already starts with it.
403 Invalid Host header, possible DNS rebinding attack detected
This is the 403 from my first paragraph. Since MLflow 3.5 the server validates the Host header, and its default allow list is localhost plus private IP ranges. My first unit had no --allowed-hosts, so the moment nginx forwarded Host: mlflow.example.com, MLflow refused it:

The nginx Server header in that response fools you into blaming nginx, but the body text and the fastapi_security warning in the journal come from MLflow. Adding your hostname to --allowed-hosts fixes it. The protection only exists in the default uvicorn server, so if you switch to --gunicorn-opts or --waitress-opts it silently goes away.
Request error INTERNAL_ERROR in the UI
With the host fixed, the UI loaded and then failed on its own API calls. The browser sends an Origin: https://mlflow.example.com header on the UI’s POST requests, MLflow treated that as cross-origin, logged Blocked cross-origin request from https://mlflow.example.com, and the page showed this:

The fix is the --cors-allowed-origins https://mlflow.example.com flag in the unit. After it, a POST to /ajax-api/2.0/mlflow/runs/search with that Origin header returned 200 on both releases. Behind any TLS proxy you need both flags; one without the other gives you either a 403 page or a half-working UI.
MLflow basic auth or nginx basic auth?
Since nginx already sits in front, why not drop an auth_basic line and an htpasswd file into the server block and skip the MLflow auth app? Because that is one shared gate. nginx checks a password and passes the request through; MLflow never learns who you are, so it can’t keep one person out of another team’s experiment or let a CI account write runs while analysts only read them. The MLflow authentication docs describe what the built-in app adds on top of a password:
| Question | nginx auth_basic | MLflow --app-name basic-auth |
|---|---|---|
| Accounts | Lines in an htpasswd file | Users in a database, created through /api/2.0/mlflow/users/create or the /signup page |
| Permissions | Per path or HTTP method at best, no per-experiment rights | READ, USE, EDIT, MANAGE or NO_PERMISSIONS per experiment, registered model, prompt and scorer, plus roles from 3.13.0 |
| Default for a new user | Everything | default_permission in basic_auth.ini (READ out of the box) |
| Creator rights | None | MANAGE on the experiments and models a user creates |
| Where it is stored | A file on the proxy | database_uri, here PostgreSQL mlflow_auth |
The MLflow app only guards what MLflow itself serves. Garage stays out of its reach, which is why the S3 API is bound to 127.0.0.1 and clients fetch artifacts through the tracking server’s proxy instead of from the bucket. Don’t stack the two either. MLflow clients log in by sending MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD in the HTTP Authorization header, and a request carries one of those, so an nginx password and an MLflow password can’t both ride on it. Stacking only works if you mirror every account and password in both htpasswd and MLflow, or have nginx overwrite the header with one fixed MLflow login, which throws away the per-user permissions. My choice is the MLflow app alone, with nginx doing TLS and nothing else. I did not run the nginx auth_basic variant on the lab VMs, so the left column of that table comes from how the directive works, not from a capture.
Checking basic auth and adding users
With --app-name basic-auth, every request needs a user, and the API and UI share the same accounts. A quick curl from anywhere shows whether the lock is on:
curl -s -o /dev/null -w "anon %{http_code}\n" "https://${MLFLOW_FQDN}/api/2.0/mlflow/experiments/search?max_results=1"
curl -s -o /dev/null -w "admin %{http_code}\n" -u "admin:${MLFLOW_ADMIN_PASS}" "https://${MLFLOW_FQDN}/api/2.0/mlflow/experiments/search?max_results=1"
Anonymous gets 401, admin gets 200. Any other pair, especially 200 for the anonymous call, means the unit is not running with the auth app. Once admin answers 200, MLFLOW_AUTH_ADMIN_PASSWORD has done its only job, which is creating the admin user on first start, so delete that line from /etc/mlflow/mlflow.env, restart mlflow and rotate the admin password through the 2.0/mlflow/users/update-password endpoint.
anon 401
admin 200
Do not share the admin account. Create one user per person (or per CI pipeline) through the REST API, logged in as admin.
curl -s -u "admin:${MLFLOW_ADMIN_PASS}" -X POST "https://${MLFLOW_FQDN}/api/2.0/mlflow/users/create" \
-H "Content-Type: application/json" -d '{"username":"philip","password":"Philip-Pass-2026"}'
The new user starts with the READ default from basic_auth.ini on other people’s experiments and full rights on the ones it creates. That’s the account the client in the next section logs in with, so nothing in the training code ever holds the admin password.
Logging the German Credit model from a client
I wanted a real model in the registry, not a toy, so I trained on the UCI Statlog German Credit data: 1,000 loan applicants, 20 features, and a published cost matrix where approving a bad borrower costs five times more than rejecting a good one. Prof. H. Hofmann donated the Statlog German Credit dataset to the UCI Machine Learning Repository in 1994, and it is licensed CC BY 4.0, so you can reuse it as long as you credit it. I ran the client on box2, the 24.04 VM, against the server on box1, so everything went over HTTPS like a laptop would. The client needs only uv (the same pipx line as on the server, or any uv install you already have), MLflow and the ML libraries. No boto3 and no AWS keys.
mkdir -p ~/credit && cd ~/credit
uv venv .venv --python /usr/bin/python3
uv pip install --python .venv/bin/python "mlflow==3.18.0" scikit-learn pandas
source .venv/bin/activate
The client finds the server and its credentials through three environment variables. Put them in your shell profile on a workstation.
export MLFLOW_TRACKING_URI="https://mlflow.example.com"
export MLFLOW_TRACKING_USERNAME="philip"
export MLFLOW_TRACKING_PASSWORD="Philip-Pass-2026"
Now the training script. It downloads the dataset, builds a scikit-learn pipeline, logs params and four metrics, and registers the model as credit-risk in one call:
vim train_credit.py
The uci_cost metric applies the dataset’s own 5:1 cost matrix, which is the number I’d use to pick a winner here, not accuracy:
import io
import sys
import urllib.request
import zipfile
import mlflow
import pandas as pd
from mlflow.models import infer_signature
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
URL = "https://archive.ics.uci.edu/static/public/144/statlog+german+credit+data.zip"
COLS = [
"checking_status", "duration", "credit_history", "purpose", "credit_amount",
"savings", "employment", "installment_rate", "personal_status", "other_debtors",
"residence_since", "property", "age", "other_installments", "housing",
"existing_credits", "job", "dependents", "telephone", "foreign_worker", "target",
]
NUMERIC = ["duration", "credit_amount", "installment_rate", "residence_since",
"age", "existing_credits", "dependents"]
# MLflow 3 saves sklearn models with skops, which refuses this type unless trusted
TRUSTED = ["sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor"]
def load():
raw = urllib.request.urlopen(URL, timeout=60).read()
with zipfile.ZipFile(io.BytesIO(raw)) as z:
df = pd.read_csv(z.open("german.data"), sep=" ", header=None, names=COLS)
# UCI codes 1 = good, 2 = bad; predict "bad"
y = (df.pop("target") == 2).astype(int)
for c in NUMERIC:
df[c] = df[c].astype("float64")
return df, y
def build(kind):
cats = [c for c in COLS[:-1] if c not in NUMERIC]
prep = ColumnTransformer([
("num", StandardScaler(), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore"), cats),
])
if kind == "logreg":
clf = LogisticRegression(C=0.5, max_iter=1000, class_weight="balanced")
else:
clf = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.05,
max_depth=4, class_weight="balanced",
random_state=42)
return Pipeline([("prep", prep), ("clf", clf)])
def main(kind):
X, y = load()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25,
stratify=y, random_state=42)
mlflow.set_experiment("credit-risk")
with mlflow.start_run(run_name=f"german-credit-{kind}") as run:
model = build(kind).fit(X_tr, y_tr)
proba = model.predict_proba(X_te)[:, 1]
pred = (proba >= 0.5).astype(int)
# UCI cost matrix: a bad customer scored good costs 5, the reverse costs 1
cost = int(((pred == 0) & (y_te == 1)).sum() * 5 + ((pred == 1) & (y_te == 0)).sum())
mlflow.log_params({"model": kind, **{k: v for k, v in model.named_steps["clf"].get_params().items()
if k in ("C", "max_iter", "learning_rate", "max_depth", "class_weight")}})
mlflow.log_metrics({
"roc_auc": roc_auc_score(y_te, proba),
"accuracy": accuracy_score(y_te, pred),
"f1_bad": f1_score(y_te, pred),
"uci_cost": cost,
})
signature = infer_signature(X_te, model.predict(X_te))
trusted = TRUSTED if kind == "hgb" else None
info = mlflow.sklearn.log_model(model, name="model", signature=signature,
input_example=X_te.head(3),
registered_model_name="credit-risk",
skops_trusted_types=trusted)
print(f"run_id={run.info.run_id} model_uri={info.model_uri} version={info.registered_model_version}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "logreg")
Train the logistic regression first.
python train_credit.py logreg
The first run creates the experiment and the registered model, and version 1 is ready about eight seconds later. The pip warning is harmless; uv venvs don’t ship pip, so MLflow can’t read its version for conda.yaml:
2026/11/12 11:38:22 INFO mlflow.tracking.fluent: Experiment with name 'credit-risk' does not exist. Creating a new experiment.
2026/11/12 11:38:43 WARNING mlflow.utils.environment: Failed to resolve installed pip version. ``pip`` will be added to conda.yaml environment spec without a version specifier.
Successfully registered model 'credit-risk'.
2026/11/12 11:38:51 INFO mlflow.store.model_registry.abstract_store: Waiting up to 300 seconds for model version to finish creation. Model name: credit-risk, version 1
Created version '1' of model 'credit-risk'.
run_id=b77ff47e30604827855cbc4b039cc4bf model_uri=models:/m-c1bf7a6f8e294841bde0f83b2100b6bf version=1
Notice the model URI: MLflow 3 gives every logged model its own ID (m-...), separate from the run. Then train the gradient boosting challenger with python train_credit.py hgb, which becomes version 2. In the UI, switch the sidebar toggle from GenAI to Model training (1) or you won’t see classic runs at all, then open german-credit-logreg (2):

- 1Model training
- 2german-credit-logreg
The run page holds the four metrics and the params the script logged, plus the registered model version it produced.

On the server side, both models sit in the Garage bucket under 1/models/<model id>/artifacts/, each with an MLmodel file, environment specs, an input example and a model.skops file of 173 KB (logistic regression) or 2 MB (gradient boosting). The training client never touched S3 directly.
Registering and promoting with aliases, not stages
If you learned MLflow on Staging and Production stages, they’re gone in spirit. The MLflow model registry workflow docs say “Model Stages are deprecated and will be removed in a future major release”, and the UI now labels the field “Stage (deprecated)”. Aliases replace them: a named, movable pointer such as champion that you can attach to any version. Before promoting anything, I compared the two runs with compare_runs.py, which sorts the experiment by the cost metric.
import mlflow
runs = mlflow.search_runs(experiment_names=["credit-risk"], order_by=["metrics.uci_cost ASC"])
cols = ["tags.mlflow.runName", "metrics.roc_auc", "metrics.accuracy", "metrics.f1_bad", "metrics.uci_cost"]
print(runs[cols].rename(columns=lambda c: c.split(".")[-1]).round(4).to_string(index=False))
The terminal below shows that comparison, then the alias script and the champion load, all run from box2 against the server.

The boring model won. Logistic regression had the higher ROC AUC (0.8095 against 0.7936) and, more importantly, a misclassification cost of 126 against 186 on the 250 test applicants. Gradient boosting was more confident and more wrong about the expensive class. So version 1 becomes champion and version 2 stays around as challenger for shadow scoring. The promote.py script that sets them is short.
from mlflow import MlflowClient
client = MlflowClient()
client.set_registered_model_alias("credit-risk", "champion", 1)
client.set_registered_model_alias("credit-risk", "challenger", 2)
for alias in ("champion", "challenger"):
mv = client.get_model_version_by_alias("credit-risk", alias)
print(f"{alias:<11} -> version {mv.version} run {mv.run_id[:8]} status {mv.status}")
Serving code never names a version. It asks for models:/credit-risk@champion, so promoting a new model is one alias move with no redeploy of the code that loads it. This is score_champion.py, which printed [1] (bad risk) for a 24 year old asking for 9,000 DM over 36 months with an overdrawn checking account:
import mlflow
import pandas as pd
model = mlflow.pyfunc.load_model("models:/credit-risk@champion")
applicant = pd.DataFrame([{
"checking_status": "A11", "duration": 36.0, "credit_history": "A32",
"purpose": "A43", "credit_amount": 9000.0, "savings": "A61",
"employment": "A72", "installment_rate": 4.0, "personal_status": "A93",
"other_debtors": "A101", "residence_since": 2.0, "property": "A124",
"age": 24.0, "other_installments": "A143", "housing": "A151",
"existing_credits": 1.0, "job": "A173", "dependents": 1.0,
"telephone": "A191", "foreign_worker": "A201",
}])
print("loaded", model.metadata.model_uuid, "from run", model.metadata.run_id[:8])
print("prediction (1 = bad credit risk):", model.predict(applicant).tolist())
You can do the same promotion by hand. Open Model registry (1), pick credit-risk, and both aliases show in the Aliases column; the Edit aliases pencil (2) on a version row opens the editor:

- 1Model registry
- 2Edit aliases
Type the new name into the alias field (1), here a candidate alias, and press Save aliases (2). Moving champion to another version this way detaches it from the old one automatically, because an alias points at exactly one version:

- 1candidate alias
- 2Save aliases
The version page ties everything together: the alias, the deprecated stage field still showing None, and a link back to the source run with its metrics. That link is what an auditor asks for when a loan decision is questioned months later:

If you plan to serve the champion on Kubernetes rather than from a Python process, our KServe on Kubernetes walkthrough covers the inference side, and the registry URI stays the same.
Troubleshooting the errors I hit
The psycopg, Host header and CORS errors are covered where they happen above. Three more stopped me, and each one sends you to the wrong machine first. Here is where to look:
- Unit restarting in a loop: the server journal
- Artifact upload hangs on the client: the server journal again
- One model logs and another fails: the client traceback
Each H3 below carries the exact error text, so a search for it lands on the fix.
MLflow Authentication needs a password to create the admin user
I started basic auth before adding the admin password line, and the unit crashed in a loop with this in the journal.
mlflow.exceptions.MlflowException: MLflow Authentication needs a password to create the admin user 'admin', but none is configured (or it is empty). MLflow ships no default admin password. Set the MLFLOW_AUTH_ADMIN_PASSWORD environment variable, or set `admin_password` in the configuration file referenced by MLFLOW_AUTH_CONFIG_PATH, and restart the server.
Old guides log in with admin/password1234. That default is gone, which is good news on a server scanners find within minutes. Add MLFLOW_AUTH_ADMIN_PASSWORD (12 characters or more) to /etc/mlflow/mlflow.env, then run sudo systemctl reset-failed mlflow and start it again.
Could not connect to the endpoint URL: s3.garage.amazonaws.com
I commented out MLFLOW_S3_ENDPOINT_URL on purpose to see what happens. Without it, boto3 builds an AWS hostname from the bucket and the region, which here was garage, and the server logged this on the first upload:
botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://mlflow-artifacts.s3.garage.amazonaws.com/1/49396fb1a6104078a32d2d64178baa5a/artifacts/smoke.txt"
The client only sees “too many 500 error responses” from /api/2.0/mlflow-artifacts/ after several minutes of retries, which points you at the wrong machine. When artifact uploads hang, read the server journal first. The variable must be in the server’s environment file, not on the client, because with --serve-artifacts the server is the only S3 client.
UntrustedTypesFoundException when logging a HistGradientBoosting model
The logistic regression logged fine, but the gradient boosting run failed at log_model. MLflow 3.18 serializes scikit-learn models with skops instead of cloudpickle by default, reloads each one to check it, and skops refuses types it hasn’t been told to trust:
mlflow.exceptions.MlflowException: The saved sklearn model references untrusted types. If you are sure loading these types is safe, set the 'skops_trusted_types' parameter when calling 'log_model' or 'save_model' to the list of trusted types. Root error: Untrusted types found in the file: ['sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor'].
The full message explains why: the tree predictor stores raw node indices that a malicious file could point out of bounds. Pass exactly the listed type in skops_trusted_types, as the script does, and never the whole output of get_untrusted_types(). The failed run still appears in the experiment, so delete it from the UI or with MlflowClient().delete_run() before comparing runs.
Backing up and upgrading the server
What do you actually need to rebuild this server from nothing? Three things, and losing any one of them hurts in a different way:
- Both PostgreSQL databases (runs, registry, users)
- The Garage meta and data directories (the model files)
/etc/mlflowand/etc/garage(secrets and keys)
Without the databases the registry forgets which run produced which model. Without the bucket every models:/ URI points at nothing. The databases are small enough to dump in a second.
sudo mkdir -p /var/backups/mlflow && sudo chown postgres /var/backups/mlflow
sudo -u postgres pg_dump -Fc -f /var/backups/mlflow/mlflow-$(date +%F).dump mlflow
sudo -u postgres pg_dump -Fc -f /var/backups/mlflow/mlflow_auth-$(date +%F).dump mlflow_auth
sudo docker exec -e RUST_LOG=warn garage /garage meta snapshot --all
ls -lh /var/backups/mlflow
The Garage snapshot gives a consistent copy of its metadata database under /var/lib/garage/meta/snapshots/, so you can copy the meta and data directories without stopping the container. After two runs and two model versions the dumps were tiny, but look at the mode bits in this listing.
total 192K
-rw-r--r-- 1 postgres postgres 154K Nov 12 11:47 mlflow-2026-11-12.dump
-rw-r--r-- 1 postgres postgres 36K Nov 12 11:47 mlflow_auth-2026-11-12.dump
Both files are world-readable, and the mlflow_auth dump holds every user’s password hash. Close the directory with sudo chmod 700 /var/backups/mlflow, then copy it off the box together with the Garage directories, /etc/mlflow and /etc/garage. A backup that lives only on the server it protects isn’t one.
Upgrading MLflow is a pip install into the venv plus a schema migration. Take the dumps first and stop the service. Then rerun the uv pip install line from the install section with the new version pin, and run db upgrade as the mlflow user with the environment file loaded before starting it again. These are the stop, migrate and start commands I ran on box1.
sudo systemctl stop mlflow
sudo -u mlflow bash -c 'set -a; . /etc/mlflow/mlflow.env; /opt/mlflow/bin/mlflow db upgrade "$MLFLOW_BACKEND_STORE_URI"'
sudo systemctl start mlflow
On an up-to-date schema it prints Updating database tables and finishes in about 11 seconds, which is mostly Python import time. If it fails halfway, restore the mlflow dump with pg_restore --clean and stay on the old version until you know why.
What I still don’t know
A few things I couldn’t settle in two days on these boxes:
- How much RAM job execution needs on a busy GenAI team, since I only measured it idle
- Whether 2 uvicorn workers hold up past 20 concurrent UI users; I never loaded it that hard
- How Garage behaves past a few hundred GB on one node; my bucket held 2 MB
- Whether the skops trust list will need more types for XGBoost or LightGBM pipelines
If you run notebooks against this server, set the three tracking variables in the Jupyter environment too; our JupyterLab on Ubuntu 26.04 notes show where they go. If your training rows come out of a Spark job rather than a zip file, our PySpark ETL guide with Pandera and OpenLineage turns the same German Credit data into a credit_features table behind a quality gate, and once credit_features becomes training input for a credit model, this MLflow tracking server is where those runs belong. For the theory behind registries, drift and retraining, the picks in our MLOps book list go deeper than any docs page, and the machine learning books round-up covers the modelling side that this credit example only touched.