DevOps
MinIO as a Self-Hosted S3 Backend in Docker
AWS egress costs and vendor lock-in are avoidable. Run MinIO as a drop-in S3-compatible object store in Docker, wired into your existing infra stack with zero app-code changes.
- Published
- Reading
- 8 min
- Author
- Fidelis Uwem Joseph
Series · Part 9 of 9FastAPI in Production
- FastAPI Layered Architecture — Routes, Services, and Repositories
- Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
- Alembic Async Migrations and Idempotent Database Seeding in FastAPI
- Stateless OTP Login in FastAPI with JWT and Redis
- Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
- Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
- Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
- Mailpit as a Dev SMTP Catch-All Behind Traefik
- MinIO as a Self-Hosted S3 Backend in Docker
S3 is the de facto standard for object storage, but the AWS dependency and egress costs add up fast. MinIO is an S3-compatible object store you run yourself. Your app code changes nothing: same SDK, same API calls, different endpoint URL. This post covers running MinIO in Docker with a persistent volume, health checks, and a Console UI, then connecting a Python app to it using boto3. Assumed knowledge: Docker Compose basics, basic familiarity with S3 concepts (buckets, objects, access keys).
Prerequisites
- Docker Engine 24+
- Docker Compose v2
- A shared Docker network your app containers can join (this post uses
infra_net) - Traefik v3 running as your reverse proxy
Background
MinIO implements the Amazon S3 REST API specification. Any client that speaks S3: boto3, the AWS CLI, @aws-sdk/client-s3, the Laravel S3 storage driver, Terraform’s S3 backend. All of them work against MinIO by changing one config value, the endpoint URL.
MinIO runs in two modes. Single-node mode (used here) runs one process writing to one volume. It is simple, low-overhead, and sufficient for dev stacks and small production workloads. Distributed mode spans multiple nodes for high availability and erasure coding. That matters when you cannot afford data loss on hardware failure. It does not matter for a team sharing a dev server.
Implementation
1. MinIO service definition
minio: image: minio/minio:latest container_name: minio restart: unless-stopped command: server /data --console-address ":9001" environment: MINIO_ROOT_USER: ${MINIO_ROOT_USER} MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD} volumes: - minio_data:/data networks: - infra_net ports: - "127.0.0.1:9000:9000" - "127.0.0.1:9001:9001" healthcheck: test: ["CMD", "mc", "ready", "local"] interval: 15s timeout: 5s retries: 1 start_period: 15s--console-address ":9001" pins the Console to a fixed port. Without it, MinIO binds the Console to a random port on every restart, breaking SSH tunnel aliases and any tooling that expects a consistent address.
start_period: 15s matters here. MinIO takes several seconds to initialize on first boot while writing the data directory. Without it, Docker marks the container unhealthy before initialization completes.
2. Environment variables
MINIO_ROOT_USER=minioadminMINIO_ROOT_PASSWORD=changeme_use_32_chars_minimum3. Creating a bucket and service account
Access the Console at http://localhost:9001 via SSH tunnel:
ssh -L 9001:127.0.0.1:9001 user@your-server -N &Log in with the root credentials.
Create a bucket: navigate to Buckets, then Create Bucket. Set the access policy to Private. Public buckets expose all objects to unauthenticated HTTP requests.
Create a service account: navigate to Identity, then Service Accounts, then Create Service Account. Copy the Access Key and Secret Key immediately. MinIO only shows the secret once. These go in your app’s .env, not the root credentials.
4. Connecting a Python app
boto3 works against MinIO without any changes to how you call it. The only required difference from standard AWS usage is endpoint_url:
import boto3from botocore.config import Config
s3 = boto3.client( "s3", endpoint_url="http://minio:9000", aws_access_key_id=settings.MINIO_ACCESS_KEY, aws_secret_access_key=settings.MINIO_SECRET_KEY, region_name="us-east-1", config=Config(signature_version="s3v4"),)region_name is required by boto3 but ignored by MinIO. "us-east-1" is a safe placeholder.
For apps running outside Docker, swap the endpoint:
endpoint_url="http://localhost:9000"5. Uploading and retrieving objects
def upload_file(local_path: str, object_key: str, bucket: str = "app-uploads") -> str: s3.upload_file(local_path, bucket, object_key) return object_key
def get_presigned_url( object_key: str, bucket: str = "app-uploads", expires: int = 3600) -> str: return s3.generate_presigned_url( "get_object", Params={"Bucket": bucket, "Key": object_key}, ExpiresIn=expires, )6. Using the AWS CLI against MinIO
aws configure --profile minio# AWS Access Key ID: your-service-account-key# AWS Secret Access Key: your-service-account-secret# Default region name: us-east-1# Default output format: json# List bucketsaws --profile minio --endpoint-url http://localhost:9000 s3 ls
# Upload a fileaws --profile minio --endpoint-url http://localhost:9000 s3 cp file.txt s3://app-uploads/
# List objects in a bucketaws --profile minio --endpoint-url http://localhost:9000 s3 ls s3://app-uploads/Testing and Verification
Confirm the container is healthy:
docker compose ps minio# NAME STATUS# minio running (healthy)Run a full upload-download round-trip:
echo "hello minio" > /tmp/test.txt
aws --profile minio --endpoint-url http://localhost:9000 \ s3 cp /tmp/test.txt s3://app-uploads/test.txt
aws --profile minio --endpoint-url http://localhost:9000 \ s3 cp s3://app-uploads/test.txt /tmp/test-retrieved.txt
diff /tmp/test.txt /tmp/test-retrieved.txt# no output means files are identicalVerify Console access:
curl -I http://localhost:9001# HTTP/1.1 200 OKPitfalls
Production Considerations
Enable TLS by mounting a certificate and key at /root/.minio/certs/public.crt and /root/.minio/certs/private.key. MinIO picks them up automatically on startup. The only required app-side change is swapping http:// to https:// in the endpoint URL.
Enable Prometheus metrics by setting MINIO_PROMETHEUS_AUTH_TYPE=public and scraping http://minio:9000/minio/v2/metrics/cluster. The endpoint exposes object counts, storage utilization, request rates, and error rates. Enough to know when you are approaching capacity before you hit it.
Enable bucket versioning for any bucket storing user uploads. Versioning turns every overwrite into a new object version and gives you soft-delete and recovery without a separate backup strategy. Pair it with a lifecycle policy that expires non-current versions after 30 days to prevent unbounded storage growth.
Lifecycle policies also handle incomplete uploads. Presigned PUT URLs for client-side uploads will sometimes never complete: the user abandoned the form, the network dropped, the client crashed. A lifecycle rule that expires objects tagged status=pending after 24 hours keeps the bucket clean automatically.
Going deeper
Script the setup instead of clicking through it
Step 3 creates the bucket and service account in the web Console. That works once, but nobody remembers the clicks when the server is rebuilt. It is also less reliable than it used to be: in 2025 MinIO removed most administration features from the community Console, leaving it as a file browser. The mc command-line client does everything the old Console did, and it can run as a one-shot container next to MinIO:
minio-init: image: minio/mc:latest depends_on: minio: condition: service_healthy environment: MINIO_ROOT_USER: ${MINIO_ROOT_USER} MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD} APP_SECRET_KEY: ${MINIO_APP_SECRET_KEY} entrypoint: > /bin/sh -c " mc alias set local http://minio:9000 $$MINIO_ROOT_USER $$MINIO_ROOT_PASSWORD && mc mb --ignore-existing local/app-uploads && mc admin policy create local app-uploads-rw /policies/app-uploads-rw.json || true && mc admin user add local app-uploads $$APP_SECRET_KEY && mc admin policy attach local app-uploads-rw --user app-uploads || true " volumes: - ./minio/policies:/policies:ro networks: - infra_net$$ escapes the dollar sign so Compose passes the variable to the shell inside the container instead of substituting it itself. --ignore-existing and the || true guards make the script safe to run on every docker compose up.
The policy gives the app exactly what it needs, on one bucket, and nothing else:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::app-uploads/*"] }, { "Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::app-uploads"] } ]}The app then uses app-uploads as its access key and MINIO_APP_SECRET_KEY as its secret. If those leak, the damage is limited to one bucket, and the root credentials never leave the server.
Presigned URLs that work outside Docker
The warning in step 4 is right about the problem and wrong about the fix. MINIO_SERVER_URL changes the URLs MinIO itself generates, such as Console redirects. Presigned URLs are not generated by MinIO at all: boto3 builds and signs them locally, using its own endpoint_url. The hostname is part of what gets signed, so you cannot rewrite minio to a public name afterwards either. The signature would no longer match.
Use two clients. The internal one talks to MinIO over the Docker network. The public one never makes a request. It only signs URLs, using the hostname browsers will use:
from botocore.config import Config
common = dict( aws_access_key_id=settings.MINIO_ACCESS_KEY, aws_secret_access_key=settings.MINIO_SECRET_KEY, region_name="us-east-1", config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),)
s3 = boto3.client("s3", endpoint_url="http://minio:9000", **common) # uploads, deletess3_public = boto3.client("s3", endpoint_url=settings.S3_PUBLIC_URL, **common) # signing only
def get_presigned_url(key: str, bucket: str = "app-uploads", expires: int = 3600) -> str: return s3_public.generate_presigned_url( "get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=expires )S3_PUBLIC_URL is whatever the browser can reach, for example https://files.example.com routed through Traefik to minio:9000.
addressing_style: path matters for any non-AWS endpoint. By default boto3 may use virtual-hosted URLs (app-uploads.files.example.com), which need wildcard DNS and a matching certificate. Path style (files.example.com/app-uploads/key) works with a single hostname.
Let clients upload directly
Routing large uploads through your API ties up workers and doubles bandwidth. A presigned PUT lets the browser or mobile app send the file straight to MinIO:
def presign_upload(key: str, content_type: str, bucket: str = "app-uploads") -> str: return s3_public.generate_presigned_url( "put_object", Params={"Bucket": bucket, "Key": key, "ContentType": content_type}, ExpiresIn=900, )curl -X PUT -H "Content-Type: image/png" --upload-file avatar.png "$PRESIGNED_URL"The client must send the same Content-Type that was signed, or MinIO rejects the upload with SignatureDoesNotMatch. Generate the key on the server (uploads/{user_id}/{uuid4()}.png) rather than trusting a filename from the client. Browsers also need CORS: set MINIO_API_CORS_ALLOW_ORIGIN on the MinIO service to your app’s origin.
Versioning, lifecycle and stale uploads with mc
The production section recommends versioning and lifecycle rules. With mc they are three commands, and they can go in the same init container:
mc version enable local/app-uploadsmc ilm rule add local/app-uploads --noncurrent-expire-days 30 # keep old versions for 30 daysmc ilm rule ls local/app-uploadsIncomplete multipart uploads from abandoned presigned uploads are cleaned up automatically by MinIO. The default expiry is 24 hours, adjustable with MINIO_API_STALE_UPLOADS_EXPIRY.
Back up somewhere else
Versioning protects against overwrites and deletes. It does not protect against losing the server. mc mirror copies a bucket to another S3-compatible target and can keep it in sync:
mc alias set offsite https://s3.eu-central-1.wasabisys.com "$OFFSITE_KEY" "$OFFSITE_SECRET"mc mirror --overwrite --remove local/app-uploads offsite/app-uploads-backupRun it from cron or a scheduled container. Drop --remove if you want the backup to keep objects deleted from the source.
Pin the MinIO image to a release tag (minio/minio:RELEASE.2025-…) instead of latest. Distribution of MinIO’s community images also changed during 2025, so check that the tag you rely on is still published before rebuilding a server.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Presigned URL fails in the browser | URL signed with http://minio:9000 | Sign with a client using the public endpoint |
SignatureDoesNotMatch on upload | Host, Content-Type or clock differs from what was signed | Sign with the public host, send the signed headers, sync server time |
| Bucket name appears as a subdomain | Virtual-hosted addressing | addressing_style: path |
| Browser upload blocked | CORS | Set MINIO_API_CORS_ALLOW_ORIGIN |
| Console has no Identity menu | Community Console reduced in 2025 | Use mc admin |
AccessDenied for the app | Policy missing an action or the bucket ARN | Check both the bucket and bucket/* resources |
Wrapping Up
MinIO gives you S3-compatible object storage with no AWS dependency and no per-request egress cost. Set endpoint_url to http://minio:9000, create service accounts through the Console, and your application code never knows it is not talking to AWS.
The next piece of the stack is email testing in development: