MinIO: Self-Hosted Object Storage for ML Pipelines
MinIO is an open-source object storage solution fully compatible with the Amazon S3 API. In the machine learning ecosystem, MinIO has become a popular choice for storing datasets, model artifacts, and experiment results due to its high performance, easy deployment, and full compatibility with ML tools such as MLflow, PyTorch, and TensorFlow.
This article covers how to use MinIO as a storage foundation for ML pipelines, from installation to building a model registry and dataset versioning system.
Why MinIO for ML?
In machine learning workflows, we frequently deal with large files: image datasets, model weights, training checkpoints, and experiment logs. Cloud object storage like Amazon S3 is the standard solution, but costs can escalate quickly and there is vendor lock-in.
MinIO provides a compelling alternative:
- S3-compatible: All tools that support S3 automatically work with MinIO
- Self-hosted: Data stays on your own infrastructure, suitable for data sovereignty regulations
- High performance: Optimized for high throughput on modern hardware
- Free and open-source: No licensing costs for community usage
Installing MinIO
Installation with Docker
The easiest way to get started with MinIO is using Docker:
docker run -d \
--name minio \
-p 9000:9000 \
-p 9001:9001 \
-v minio-data:/data \
-e "MINIOROOTUSER=minioadmin" \
-e "MINIOROOTPASSWORD=minioadmin123" \
quay.io/minio/minio server /data --console-address ":9001"
For a more structured setup, use Docker Compose:
version: '3.8'
services:
minio:
image: quay.io/minio/minio
containername: minio
ports:
- "9000:9000"
- "9001:9001"
environment:
MINIOROOTUSER: minioadmin
MINIOROOTPASSWORD: minioadmin123
volumes:
- minio-data:/data
command: server /data --console-address ":9001"
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 30s
timeout: 20s
retries: 3
volumes:
minio-data:
Run it with:
docker-compose up -d
Binary Installation
For direct installation on a Linux server:
wget https://dl.min.io/server/minio/release/linux-amd64/minio
chmod +x minio
sudo mv minio /usr/local/bin/
Create data directory
sudo mkdir -p /data/minio
Run MinIO
MINIOROOTUSER=minioadmin MINIOROOTPASSWORD=minioadmin123 \
minio server /data/minio --console-address ":9001"
To run MinIO as a systemd service:
[Unit]
Description=MinIO Object Storage
After=network.target
[Service]
Type=simple
User=minio-user
Group=minio-user
Environment="MINIOROOTUSER=minioadmin"
Environment="MINIOROOTPASSWORD=minioadmin123"
ExecStart=/usr/local/bin/minio server /data/minio --console-address ":9001"
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable minio
sudo systemctl start minio
MinIO Console UI
Once MinIO is running, access the Console UI at http://localhost:9001. The Console provides a visual interface for:
- Creating and managing buckets
- Uploading and downloading objects
- Setting access policies
- Monitoring performance and storage usage
- Configuring event notifications
- Managing users and groups
Log in with the configured credentials (default: minioadmin / minioadmin123).
The Console UI is particularly useful for data science teams who are not comfortable with the command line. They can directly browse datasets, preview files, and manage buckets without additional tools.
MinIO Client (mc)
MinIO provides the mc command-line tool for administration:
# Install mc
wget https://dl.min.io/client/mc/release/linux-amd64/mc
chmod +x mc
sudo mv mc /usr/local/bin/
Configure alias
mc alias set local http://localhost:9000 minioadmin minioadmin123
Basic operations
mc mb local/ml-datasets # Create bucket
mc ls local/ # List buckets
mc cp data.csv local/ml-datasets # Upload file
mc cat local/ml-datasets/data.csv # View file contents
Python SDK (minio-py)
Installation
pip install minio
Connection and Configuration
from minio import Minio
client = Minio(
"localhost:9000",
accesskey="minioadmin",
secretkey="minioadmin123",
secure=False # True if using HTTPS
)
Verify connection
buckets = client.listbuckets()
print(f"Connected to MinIO. Number of buckets: {len(buckets)}")
Bucket Operations
from minio import Minio
from minio.error import S3Error
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
Create bucket
bucketname = "ml-datasets"
if not client.bucketexists(bucketname):
client.makebucket(bucketname)
print(f"Bucket '{bucketname}' created successfully")
else:
print(f"Bucket '{bucketname}' already exists")
List all buckets
for bucket in client.listbuckets():
print(f" - {bucket.name} (created: {bucket.creationdate})")
Remove bucket (must be empty)
client.removebucket("old-bucket")
Object Upload and Download
import os
from minio import Minio
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
Upload file
client.fputobject(
"ml-datasets",
"training/images/cat001.jpg",
"/local/path/cat001.jpg",
contenttype="image/jpeg"
)
Upload from bytes/stream
import io
data = b"column1,column2\ndata1,data2\n"
client.putobject(
"ml-datasets",
"training/labels.csv",
io.BytesIO(data),
length=len(data),
contenttype="text/csv"
)
Download file
client.fgetobject(
"ml-datasets",
"training/images/cat001.jpg",
"/local/path/downloadedcat.jpg"
)
Download to memory
response = client.getobject("ml-datasets", "training/labels.csv")
content = response.read().decode('utf-8')
response.close()
response.releaseconn()
print(content)
List objects in bucket
objects = client.listobjects("ml-datasets", prefix="training/", recursive=True)
for obj in objects:
print(f" {obj.objectname} - {obj.size} bytes - {obj.lastmodified}")
Recursive Directory Upload
import os
from pathlib import Path
from minio import Minio
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
def uploaddirectory(bucketname, localdir, remoteprefix=""):
"""Upload an entire directory to MinIO."""
localpath = Path(localdir)
uploaded = 0
for filepath in localpath.rglob(""):
if filepath.isfile():
relative = filepath.relativeto(localpath)
objectname = f"{remoteprefix}/{relative}" if remoteprefix else str(relative)
client.fputobject(bucketname, objectname, str(filepath))
uploaded += 1
print(f" Uploaded: {objectname}")
print(f"Total {uploaded} files uploaded successfully")
Example: upload dataset
uploaddirectory("ml-datasets", "/data/imagenet-subset", "datasets/imagenet-v1")
Presigned URLs
Presigned URLs allow temporary access to objects without requiring credentials:
from datetime import timedelta
from minio import Minio
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
URL for download (GET) - valid for 2 hours
downloadurl = client.presignedgetobject(
"ml-datasets",
"models/resnet50v2.pth",
expires=timedelta(hours=2)
)
print(f"Download URL: {downloadurl}")
URL for upload (PUT) - valid for 1 hour
uploadurl = client.presignedputobject(
"ml-datasets",
"uploads/newmodel.pth",
expires=timedelta(hours=1)
)
print(f"Upload URL: {uploadurl}")
Presigned URLs are very useful for:
- Giving download access to teams without sharing credentials
- Enabling uploads from frontend applications
- Integration with CI/CD pipelines
Versioning
Versioning allows you to keep multiple versions of the same object, which is critical for tracking dataset and model changes:
# Enable versioning via mc
mc version enable local/ml-datasets
from minio import Minio
from minio.versioningconfig import VersioningConfig, ENABLED
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
Enable versioning via Python SDK
client.setbucketversioning("ml-datasets", VersioningConfig(ENABLED))
Upload multiple versions
client.fputobject("ml-datasets", "models/classifier.pth", "modelv1.pth")
client.fputobject("ml-datasets", "models/classifier.pth", "modelv2.pth")
List all versions
objects = client.listobjects("ml-datasets", prefix="models/classifier.pth",
includeversion=True)
for obj in objects:
print(f" Version: {obj.versionid} - Size: {obj.size} - Date: {obj.lastmodified}")
Download a specific version
client.fgetobject("ml-datasets", "models/classifier.pth", "modelold.pth",
versionid="specific-version-id-here")
Lifecycle Policies
Lifecycle policies automate object management, for example deleting old checkpoints:
from minio import Minio
from minio.lifecycleconfig import LifecycleConfig, Rule, Filter, Expiration
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
Delete objects under "checkpoints/" after 30 days
config = LifecycleConfig(
[
Rule(
ENABLED,
rulefilter=Filter(prefix="checkpoints/"),
ruleid="expire-old-checkpoints",
expiration=Expiration(days=30),
),
Rule(
ENABLED,
rulefilter=Filter(prefix="temp/"),
ruleid="expire-temp-files",
expiration=Expiration(days=7),
),
]
)
client.setbucketlifecycle("ml-datasets", config)
print("Lifecycle policy configured successfully")
Event Notifications (Webhooks)
MinIO supports event notifications to alert other systems when changes occur in a bucket:
# Configure webhook endpoint
mc admin config set local notifywebhook:ml-pipeline \
endpoint="http://ml-server:8080/webhook/minio" \
queuedir="/tmp/minio-events"
Restart MinIO to apply changes
mc admin service restart local
Set event notification on bucket
mc event add local/ml-datasets arn:minio:sqs::ml-pipeline:webhook \
--event put,delete --prefix "datasets/" --suffix ".csv"
Example webhook receiver with FastAPI:
from fastapi import FastAPI, Request
import json
app = FastAPI()
@app.post("/webhook/minio")
async def miniowebhook(request: Request):
event = await request.json()
for record in event.get("Records", []):
eventname = record["eventName"]
bucket = record["s3"]["bucket"]["name"]
key = record["s3"]["object"]["key"]
size = record["s3"]["object"].get("size", 0)
print(f"Event: {eventname}")
print(f"Object: {bucket}/{key} ({size} bytes)")
# Trigger pipeline based on event
if key.startswith("datasets/") and key.endswith(".csv"):
print("New dataset detected! Starting preprocessing...")
# triggerpreprocessingpipeline(bucket, key)
elif key.startswith("models/") and key.endswith(".pth"):
print("New model detected! Starting evaluation...")
# triggerevaluationpipeline(bucket, key)
return {"status": "ok"}
Integration with PyTorch
import torch
from torch.utils.data import Dataset, DataLoader
from minio import Minio
from PIL import Image
import io
import json
class MinIOImageDataset(Dataset):
"""PyTorch Dataset that reads images directly from MinIO."""
def init(self, minioclient, bucketname, prefix, transform=None):
self.client = minioclient
self.bucketname = bucketname
self.transform = transform
# List all images
self.objects = []
for obj in self.client.listobjects(bucketname, prefix=prefix, recursive=True):
if obj.objectname.lower().endswith(('.jpg', '.jpeg', '.png')):
self.objects.append(obj.objectname)
# Load labels
try:
response = self.client.getobject(bucketname, f"{prefix}/labels.json")
self.labels = json.loads(response.read().decode('utf-8'))
response.close()
response.releaseconn()
except Exception:
self.labels = {}
def len(self):
return len(self.objects)
def getitem(self, idx):
objname = self.objects[idx]
# Download image to memory
response = self.client.getobject(self.bucketname, objname)
imagedata = response.read()
response.close()
response.releaseconn()
image = Image.open(io.BytesIO(imagedata)).convert('RGB')
if self.transform:
image = self.transform(image)
# Get label
label = self.labels.get(objname.split('/')[-1], 0)
return image, label
Usage
from torchvision import transforms
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
dataset = MinIOImageDataset(client, "ml-datasets", "training/images", transform)
dataloader = DataLoader(dataset, batchsize=32, shuffle=True, numworkers=4)
for images, labels in dataloader:
print(f"Batch shape: {images.shape}, Labels: {labels.shape}")
break
Integration with TensorFlow
import tensorflow as tf
from minio import Minio
import io
import numpy as np
class MinIOTFDataLoader:
"""TensorFlow data loader from MinIO."""
def init(self, minioclient, bucketname):
self.client = minioclient
self.bucketname = bucketname
def loadnumpyarray(self, objectname):
"""Load numpy file from MinIO."""
response = self.client.getobject(self.bucketname, objectname)
data = np.load(io.BytesIO(response.read()))
response.close()
response.releaseconn()
return data
def createdataset(self, featureskey, labelskey, batchsize=32):
"""Create tf.data.Dataset from numpy files in MinIO."""
features = self.loadnumpyarray(featureskey)
labels = self.loadnumpyarray(labelskey)
dataset = tf.data.Dataset.fromtensorslices((features, labels))
dataset = dataset.shuffle(buffersize=1000)
dataset = dataset.batch(batchsize)
dataset = dataset.prefetch(tf.data.AUTOTUNE)
return dataset
Usage
client = Minio("localhost:9000", accesskey="minioadmin",
secretkey="minioadmin123", secure=False)
loader = MinIOTFDataLoader(client, "ml-datasets")
trainds = loader.createdataset(
"datasets/trainfeatures.npy",
"datasets/trainlabels.npy",
batchsize=64
)
for features, labels in trainds.take(1):
print(f"Features shape: {features.shape}")
print(f"Labels shape: {labels.shape}")
Integration with MLflow Artifact Store
MLflow supports MinIO as an artifact store through the S3-compatible interface:
# Set environment variables
export MLFLOWS3ENDPOINTURL=http://localhost:9000
export AWSACCESSKEYID=minioadmin
export AWSSECRETACCESSKEY=minioadmin123
Create bucket for MLflow
mc mb local/mlflow-artifacts
Run MLflow server
mlflow server \
--backend-store-uri sqlite:///mlflow.db \
--default-artifact-root s3://mlflow-artifacts/ \
--host 0.0.0.0 \
--port 5000
import mlflow
import os
Configuration
os.environ["MLFLOWS3ENDPOINTURL"] = "http://localhost:9000"
os.environ["AWSACCESSKEYID"] = "minioadmin"
os.environ["AWSSECRETACCESSKEY"] = "minioadmin123"
mlflow.settrackinguri("http://localhost:5000")
mlflow.setexperiment("image-classification")
Training with MLflow tracking
with mlflow.startrun(runname="resnet50-finetune"):
# Log parameters
mlflow.logparam("model", "resnet50")
mlflow.logparam("epochs", 10)
mlflow.logparam("learningrate", 0.001)
# Log metrics
mlflow.logmetric("accuracy", 0.95)
mlflow.logmetric("loss", 0.05)
# Log model artifact (automatically saved to MinIO)
mlflow.pytorch.logmodel(model, "model")
# Log additional files
mlflow.logartifact("trainingconfig.yaml")
print("Run logged successfully. Artifacts stored in MinIO!")
Multi-Node Deployment
For production, MinIO supports distributed deployment with erasure coding:
version: '3.8'
services:
minio1:
image: quay.io/minio/minio
hostname: minio1
volumes:
- minio1-data1:/data1
- minio1-data2:/data2
environment:
MINIOROOTUSER: minioadmin
MINIOROOTPASSWORD: minioadmin123
command: server http://minio{1...4}/data{1...2} --console-address ":9001"
ports:
- "9000:9000"
- "9001:9001"
minio2:
image: quay.io/minio/minio
hostname: minio2
volumes:
- minio2-data1:/data1
- minio2-data2:/data2
environment:
MINIOROOTUSER: minioadmin
MINIOROOTPASSWORD: minioadmin123
command: server http://minio{1...4}/data{1...2} --console-address ":9001"
minio3:
image: quay.io/minio/minio
hostname: minio3
volumes:
- minio3-data1:/data1
- minio3-data2:/data2
environment:
MINIOROOTUSER: minioadmin
MINIOROOTPASSWORD: minioadmin123
command: server http://minio{1...4}/data{1...2} --console-address ":9001"
minio4:
image: quay.io/minio/minio
hostname: minio4
volumes:
- minio4-data1:/data1
- minio4-data2:/data2
environment:
MINIOROOTUSER: minioadmin
MINIOROOTPASSWORD: minioadmin123
command: server http://minio{1...4}/data{1...2} --console-address ":9001"
nginx:
image: nginx
ports:
- "9000:9000"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
dependson:
- minio1
- minio2
- minio3
- minio4
volumes:
minio1-data1:
minio1-data2:
minio2-data1:
minio2-data2:
minio3-data1:
minio3-data2:
minio4-data1:
minio4-data2:
Nginx configuration as a load balancer:
upstream miniocluster {
server minio1:9000;
server minio2:9000;
server minio3:9000;
server minio4:9000;
}
server {
listen 9000;
servername ;
location / {
proxypass http://miniocluster;
proxysetheader Host $host;
proxysetheader X-Real-IP $remoteaddr;
proxysetheader X-Forwarded-For $proxyaddxforwardedfor;
proxysetheader X-Forwarded-Proto $scheme;
# For large file uploads
clientmaxbodysize 10G;
proxybuffering off;
}
}
Practical Example: Model Registry and Dataset Versioning
Let us build a complete model registry and dataset versioning system using MinIO:
import json
import hashlib
from datetime import datetime
from minio import Minio
from minio.versioningconfig import VersioningConfig, ENABLED
class MLArtifactManager:
"""ML artifact management system using MinIO."""
def init(self, endpoint, accesskey, secretkey):
self.client = Minio(endpoint, accesskey=accesskey,
secretkey=secretkey, secure=False)
self.ensurebuckets()
def ensurebuckets(self):
"""Create required buckets."""
buckets = ["ml-models", "ml-datasets", "ml-metadata"]
for bucket in buckets:
if not self.client.bucketexists(bucket):
self.client.makebucket(bucket)
self.client.setbucketversioning(
bucket, VersioningConfig(ENABLED)
)
print(f"Bucket '{bucket}' created with versioning enabled")
def computechecksum(self, filepath):
"""Compute SHA256 checksum of a file."""
sha256hash = hashlib.sha256()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256hash.update(chunk)
return sha256hash.hexdigest()
def registermodel(self, modelname, modelpath, metrics, params,
description=""):
"""Register a new model to the registry."""
checksum = self.computechecksum(modelpath)
timestamp = datetime.utcnow().isoformat()
# Upload model file
objectname = f"{modelname}/model.pth"
result = self.client.fputobject("ml-models", objectname, modelpath)
versionid = result.versionid
# Save metadata
metadata = {
"modelname": modelname,
"versionid": versionid,
"timestamp": timestamp,
"checksum": checksum,
"metrics": metrics,
"params": params,
"description": description,
"status": "staging"
}
import io
metabytes = json.dumps(metadata, indent=2).encode('utf-8')
self.client.putobject(
"ml-metadata",
f"models/{modelname}/{versionid}.json",
io.BytesIO(metabytes),
length=len(metabytes),
contenttype="application/json"
)
print(f"Model '{modelname}' registered (version: {versionid})")
return versionid
def promotemodel(self, modelname, versionid, stage="production"):
"""Promote a model to a specific stage."""
metakey = f"models/{modelname}/{versionid}.json"
response = self.client.getobject("ml-metadata", metakey)
metadata = json.loads(response.read().decode('utf-8'))
response.close()
response.releaseconn()
metadata["status"] = stage
metadata["promotedat"] = datetime.utcnow().isoformat()
import io
metabytes = json.dumps(metadata, indent=2).encode('utf-8')
self.client.putobject(
"ml-metadata", metakey,
io.BytesIO(metabytes),
length=len(metabytes),
contenttype="application/json"
)
print(f"Model '{modelname}' v{versionid} promoted to '{stage}'")
def registerdataset(self, datasetname, localdir, description=""):
"""Register a new dataset version."""
from pathlib import Path
timestamp = datetime.utcnow().isoformat()
localpath = Path(localdir)
filesuploaded = []
totalsize = 0
for filepath in localpath.rglob(""):
if filepath.isfile():
relative = filepath.relativeto(localpath)
objectname = f"{datasetname}/{relative}"
result = self.client.fputobject(
"ml-datasets", objectname, str(filepath)
)
filesuploaded.append({
"name": str(relative),
"size": filepath.stat().stsize,
"versionid": result.versionid
})
totalsize += filepath.stat().stsize
# Save dataset metadata
import io
metadata = {
"datasetname": datasetname,
"timestamp": timestamp,
"description": description,
"totalfiles": len(filesuploaded),
"totalsizebytes": totalsize,
"files": filesuploaded
}
metabytes = json.dumps(metadata, indent=2).encode('utf-8')
metakey = f"datasets/{datasetname}/{timestamp}.json"
self.client.putobject(
"ml-metadata", metakey,
io.BytesIO(metabytes),
length=len(metabytes),
contenttype="application/json"
)
print(f"Dataset '{datasetname}' registered: {len(filesuploaded)} files, "
f"{totalsize / 1024 / 1024:.2f} MB")
def listmodelversions(self, modelname):
"""List all versions of a model."""
prefix = f"models/{modelname}/"
versions = []
for obj in self.client.listobjects("ml-metadata", prefix=prefix):
response = self.client.getobject("ml-metadata", obj.objectname)
metadata = json.loads(response.read().decode('utf-8'))
response.close()
response.releaseconn()
versions.append(metadata)
return sorted(versions, key=lambda x: x["timestamp"], reverse=True)
def getproductionmodel(self, modelname):
"""Get the current production model."""
versions = self.listmodelversions(modelname)
for v in versions:
if v.get("status") == "production":
return v
return None
Full usage example
manager = MLArtifactManager("localhost:9000", "minioadmin", "minioadmin123")
Register model
version = manager.registermodel(
modelname="image-classifier",
modelpath="./resnet50trained.pth",
metrics={"accuracy": 0.956, "f1": 0.948, "loss": 0.042},
params={"epochs": 50, "lr": 0.001, "batchsize": 32},
description="ResNet50 fine-tuned on product dataset v3"
)
Promote to production
manager.promotemodel("image-classifier", version, "production")
Register dataset
manager.registerdataset(
datasetname="product-images",
localdir="./data/products/",
description="Product image dataset v3 - 10,000 images, 50 categories"
)
Check production model
prodmodel = manager.getproductionmodel("image-classifier")
if prodmodel:
print(f"Production model: {prodmodel['versionid']}")
print(f"Accuracy: {prod_model['metrics']['accuracy']}")
Tips and Best Practices
datasets/name/version/ and models/name/mc mirror for replication between clustersConclusion
MinIO is a powerful object storage solution for machine learning pipelines. With S3 compatibility, high performance, and easy deployment, MinIO enables data science teams to manage datasets and model artifacts efficiently without vendor lock-in to any specific cloud provider.
The combination of MinIO with tools like MLflow, PyTorch, and TensorFlow creates a flexible and scalable ML ecosystem. Versioning and event notification features make it ideal for building CI/CD pipelines for ML models.
Start with a single-node deployment for development, then scale to a multi-node cluster as your storage and reliability requirements grow.