Back to tutorials
Tutorial

Build RAG With Qdrant and Ollama on One VPS

Build RAG with Qdrant and Ollama on one VPS: ingest docs, search semantically, and serve a private chat API with Docker Compose.

By Anurag Singh
Updated on Dec 05, 2026
Category: Tutorial
Share article
Build RAG With Qdrant and Ollama on One VPS

Your “search” doesn’t need to ship data to a SaaS API to be useful. In this walkthrough, you’ll build RAG with Qdrant and Ollama on a single VPS. You’ll use Qdrant for vector search, Ollama for embeddings and chat, plus a small API your site or app can call.

The workflow is simple. Drop a folder of docs (text/Markdown, and PDFs if you must). Index them, then ask questions.

You’ll get answers grounded in your own content, with citations.

Everything runs on your infrastructure. You’ll also add basic, realistic security controls.

What you’ll build (architecture in plain terms)

  • Ollama: serves an embeddings model and a chat model locally over HTTP.
  • Qdrant: stores vectors and runs fast nearest-neighbor search.
  • RAG API (FastAPI): one endpoint ingests docs and stores vectors; another answers questions by retrieving the best chunks and prompting the chat model with that context.

You’ll run the stack with Docker Compose on Ubuntu.

It works well for private semantic search across internal docs, product manuals, or a support knowledge base.

VPS sizing: CPU, RAM, and disk that won’t disappoint

On a single VPS, two things dominate performance: embedding speed and token generation speed. On CPU-only machines, both are usually CPU-bound.

If you add a GPU later, the bottleneck often shifts. You can keep the rest of the architecture the same.

  • Minimum (proof-of-concept): 4 vCPU, 8 GB RAM, 60 GB NVMe. Fine for a few thousand chunks. Chat will feel sluggish on CPU.
  • Comfortable for teams: 8 vCPU, 16–32 GB RAM, 120 GB NVMe. Better concurrency, faster ingestion, and more room for models.
  • Disk: budget for both model files and vectors. Ollama models are often multiple GB each, and Qdrant grows with chunk count.

If you expect to move to GPU later, keep the deployment portable. The same app logic works on a GPU VPS or dedicated server.

You swap the inference box, not the whole system.

For that route, see Set Up vLLM OpenAI API on a GPU Dedicated Server.

Prerequisites on Ubuntu (Docker, firewall, and a domain)

This guide assumes a standard Ubuntu Server VPS. A clean install is fine.

  • A fresh VPS (Ubuntu)
  • A domain/subdomain pointed to the VPS (optional but recommended for HTTPS)
  • Root or sudo access

If SSH isn’t hardened yet, fix that first.

Password logins plus internet-facing AI endpoints is an avoidable risk.

Follow Set Up SSH Keys And Disable Password Login On VPS.

Install Docker and the Compose plugin:

sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg

sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg

echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo $VERSION_CODENAME) stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

sudo usermod -aG docker $USER

Log out and back in once so your user can run Docker.

Open only what you actually need. If you proxy through Nginx, expose 80/443 and keep Qdrant/Ollama private:

sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

If you need a VPS for this build, any plain Linux VM works well. Start with a HostMyCode VPS if you want full control.

Choose managed VPS hosting if you’d rather offload patching and baseline hardening.

Create the project structure

Keep everything under /opt/rag. Let Docker manage persistent storage for Qdrant and Ollama.

sudo mkdir -p /opt/rag/app /opt/rag/data/docs
sudo chown -R $USER:$USER /opt/rag
cd /opt/rag

Drop a few documents into /opt/rag/data/docs to start. Markdown and plain text are easiest.

PDFs can work, but extraction quality varies. That quality directly affects retrieval and answers.

Docker Compose: Qdrant + Ollama + a RAG API

Create /opt/rag/docker-compose.yml:

cat > /opt/rag/docker-compose.yml <<'YAML'
services:
  qdrant:
    image: qdrant/qdrant:latest
    restart: unless-stopped
    volumes:
      - qdrant_storage:/qdrant/storage
    networks:
      - ragnet

  ollama:
    image: ollama/ollama:latest
    restart: unless-stopped
    volumes:
      - ollama_data:/root/.ollama
    networks:
      - ragnet

  rag-api:
    build:
      context: ./app
    restart: unless-stopped
    environment:
      - QDRANT_URL=http://qdrant:6333
      - OLLAMA_URL=http://ollama:11434
      - QDRANT_COLLECTION=docs
      - EMBED_MODEL=nomic-embed-text
      - CHAT_MODEL=llama3
      - CHUNK_SIZE=900
      - CHUNK_OVERLAP=150
      - TOP_K=6
      - API_KEY=${API_KEY}
    volumes:
      - ./data/docs:/data/docs:ro
    networks:
      - ragnet

networks:
  ragnet:

volumes:
  qdrant_storage:
  ollama_data:
YAML

Notes:

  • Qdrant and Ollama stay off the public internet. You’ll expose only the API later (via Nginx).
  • API_KEY is a shared secret to filter random traffic. It’s not complete auth, but it’s a solid baseline.
  • Model names are configurable. If the tags on your system differ, update EMBED_MODEL and CHAT_MODEL.

Write the RAG API (FastAPI) with ingestion + query

Create /opt/rag/app/Dockerfile:

cat > /opt/rag/app/Dockerfile <<'DOCKER'
FROM python:3.12-slim

WORKDIR /app

RUN apt-get update \
  && apt-get install -y --no-install-recommends build-essential \
  && rm -rf /var/lib/apt/lists/*

COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt

COPY main.py /app/main.py

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
DOCKER

Create /opt/rag/app/requirements.txt:

cat > /opt/rag/app/requirements.txt <<'REQ'
fastapi==0.115.0
uvicorn[standard]==0.30.6
qdrant-client==1.12.0
requests==2.32.3
pydantic==2.8.2
python-multipart==0.0.9
REQ

Create /opt/rag/app/main.py (minimal, readable, and easy to extend later):

cat > /opt/rag/app/main.py <<'PY'
import os
import glob
import hashlib
from typing import List, Optional

import requests
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct

QDRANT_URL = os.getenv("QDRANT_URL", "http://qdrant:6333")
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://ollama:11434")
COLLECTION = os.getenv("QDRANT_COLLECTION", "docs")
EMBED_MODEL = os.getenv("EMBED_MODEL", "nomic-embed-text")
CHAT_MODEL = os.getenv("CHAT_MODEL", "llama3")
CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "900"))
CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "150"))
TOP_K = int(os.getenv("TOP_K", "6"))
API_KEY = os.getenv("API_KEY", "")

DOCS_PATH = "/data/docs"

app = FastAPI(title="RAG API")
qdrant = QdrantClient(url=QDRANT_URL)


def require_key(provided: Optional[str]):
    if not API_KEY:
        return
    if not provided or provided != API_KEY:
        raise HTTPException(status_code=401, detail="Invalid API key")


def sha1(s: str) -> str:
    return hashlib.sha1(s.encode("utf-8")).hexdigest()


def chunk_text(text: str, chunk_size: int, overlap: int) -> List[str]:
    text = "\n".join([line.rstrip() for line in text.splitlines()]).strip()
    if not text:
        return []
    chunks = []
    start = 0
    while start < len(text):
        end = min(len(text), start + chunk_size)
        chunks.append(text[start:end])
        start = end - overlap
        if start < 0:
            start = 0
        if end == len(text):
            break
    return chunks


def ollama_embed(texts: List[str]) -> List[List[float]]:
    # Ollama embeddings API expects one input per request for broad compatibility.
    vectors = []
    for t in texts:
        r = requests.post(
            f"{OLLAMA_URL}/api/embeddings",
            json={"model": EMBED_MODEL, "prompt": t},
            timeout=120,
        )
        r.raise_for_status()
        vectors.append(r.json()["embedding"])
    return vectors


def ensure_collection(vector_size: int):
    collections = [c.name for c in qdrant.get_collections().collections]
    if COLLECTION in collections:
        return
    qdrant.create_collection(
        collection_name=COLLECTION,
        vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE),
    )


class IngestResult(BaseModel):
    files: int
    chunks: int


@app.post("/ingest", response_model=IngestResult)
def ingest(x_api_key: Optional[str] = Header(default=None)):
    require_key(x_api_key)

    paths = sorted(
        glob.glob(os.path.join(DOCS_PATH, "**", "*.md"), recursive=True)
        + glob.glob(os.path.join(DOCS_PATH, "**", "*.txt"), recursive=True)
    )

    if not paths:
        raise HTTPException(status_code=400, detail="No .md or .txt files found in /data/docs")

    total_chunks = 0
    points: List[PointStruct] = []

    for p in paths:
        with open(p, "r", encoding="utf-8", errors="ignore") as f:
            text = f.read()

        chunks = chunk_text(text, CHUNK_SIZE, CHUNK_OVERLAP)
        if not chunks:
            continue

        vectors = ollama_embed(chunks)
        ensure_collection(vector_size=len(vectors[0]))

        for i, (chunk, vec) in enumerate(zip(chunks, vectors)):
            doc_id = sha1(f"{p}:{i}:{chunk[:50]}")
            payload = {
                "source": p.replace(DOCS_PATH + "/", ""),
                "chunk": i,
                "text": chunk,
            }
            points.append(PointStruct(id=doc_id, vector=vec, payload=payload))

        total_chunks += len(chunks)

    if points:
        # Upsert in batches to reduce memory spikes.
        batch_size = 64
        for i in range(0, len(points), batch_size):
            qdrant.upsert(collection_name=COLLECTION, points=points[i:i+batch_size])

    return IngestResult(files=len(paths), chunks=total_chunks)


class QueryIn(BaseModel):
    question: str


class Hit(BaseModel):
    source: str
    chunk: int
    score: float
    text: str


class QueryOut(BaseModel):
    answer: str
    hits: List[Hit]


@app.post("/query", response_model=QueryOut)
def query(inp: QueryIn, x_api_key: Optional[str] = Header(default=None)):
    require_key(x_api_key)

    q_vec = ollama_embed([inp.question])[0]

    res = qdrant.search(
        collection_name=COLLECTION,
        query_vector=q_vec,
        limit=TOP_K,
        with_payload=True,
    )

    hits: List[Hit] = []
    context_blocks = []

    for r in res:
        payload = r.payload or {}
        text = (payload.get("text") or "").strip()
        source = payload.get("source") or "unknown"
        chunk = int(payload.get("chunk") or 0)
        hits.append(Hit(source=source, chunk=chunk, score=float(r.score), text=text))
        context_blocks.append(f"[source: {source}#chunk{chunk}]\n{text}")

    if not context_blocks:
        raise HTTPException(status_code=400, detail="No results. Ingest documents first.")

    system = (
        "You answer using ONLY the provided context. "
        "If the context does not contain the answer, say you don't know. "
        "Cite sources using the [source: file#chunk] labels."
    )

    prompt = (
        f"Context:\n\n" + "\n\n".join(context_blocks) +
        f"\n\nQuestion: {inp.question}\nAnswer:"
    )

    r = requests.post(
        f"{OLLAMA_URL}/api/chat",
        json={
            "model": CHAT_MODEL,
            "messages": [
                {"role": "system", "content": system},
                {"role": "user", "content": prompt},
            ],
            "stream": False,
        },
        timeout=300,
    )
    r.raise_for_status()

    data = r.json()
    answer = data.get("message", {}).get("content", "").strip()

    return QueryOut(answer=answer, hits=hits)
PY

This API handles two jobs:

  • /ingest: reads .md/.txt from /data/docs, chunks them, embeds each chunk, and stores vectors in Qdrant.
  • /query: embeds the question, retrieves the best matches, then asks Ollama to answer using only that retrieved context.

Start the stack and pull models

Generate a strong API key. Store it in an environment file:

cd /opt/rag

API_KEY=$(openssl rand -hex 24)
echo "API_KEY=$API_KEY" | tee /opt/rag/.env

docker compose up -d --build

Now pull the models inside the Ollama container. This can take a while.

Plan for the disk usage.

docker compose exec -it ollama ollama pull nomic-embed-text
docker compose exec -it ollama ollama pull llama3

If storage is tight, move Ollama’s model cache to a larger disk early.

It’s harder to clean up later.

See move Ollama’s model cache to a disk.

Ingest your documents

With the containers running, trigger ingestion:

cd /opt/rag

curl -sS -X POST http://localhost:8000/ingest \
  -H "X-API-Key: $(grep API_KEY .env | cut -d= -f2)" | jq

If you don’t have jq installed:

sudo apt-get install -y jq

Common ingestion issues you can usually diagnose quickly:

  • Timeouts: embeddings on CPU can be slow. Ingest fewer files per run, or start with smaller documents.
  • Garbage answers: the usual culprit is ugly extracted text or oversized chunks. Try CHUNK_SIZE=700 and CHUNK_OVERLAP=120.
  • Disk fills up: models and vectors accumulate faster than you expect. Use docker system df, and follow Disk Full on VPS: Find Large Files and Free Space Safely.

Run a query and verify citations

Ask something your docs should answer:

curl -sS -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $(grep API_KEY .env | cut -d= -f2)" \
  -d '{"question":"What is our refund policy?"}' | jq -r '.answer'

Then check what the retriever returned:

curl -sS -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $(grep API_KEY .env | cut -d= -f2)" \
  -d '{"question":"What is our refund policy?"}' | jq '.hits[] | {source, chunk, score}'

If citations don’t show up, the model usually lost the instruction in a long prompt.

Lower TOP_K to 4, or reduce chunk size so the context stays tighter.

Put it behind Nginx with HTTPS (and keep Qdrant private)

Don’t expose port 8000 to the public internet without TLS and a real access plan.

A safe default is Nginx for HTTPS termination, plus the API key header.

Install Nginx:

sudo apt-get install -y nginx

Create an Nginx site at /etc/nginx/sites-available/rag-api (replace rag.example.com):

sudo tee /etc/nginx/sites-available/rag-api > /dev/null <<'NGINX'
server {
  listen 80;
  server_name rag.example.com;

  location / {
    proxy_pass http://127.0.0.1:8000;
    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;

    # Basic abuse protection
    client_max_body_size 5m;
  }
}
NGINX

sudo ln -sf /etc/nginx/sites-available/rag-api /etc/nginx/sites-enabled/rag-api
sudo nginx -t
sudo systemctl reload nginx

Add HTTPS with Let’s Encrypt:

sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d rag.example.com

If you need to sort out DNS first, do that via HostMyCode domains. Then come back and run Certbot.

Harden the endpoint: quick wins that actually matter

Once it’s reachable over HTTPS, treat it like any other production API.

A few small steps prevent most common problems.

  • Keep Qdrant and Ollama internal: don’t publish their ports. The Compose file above already avoids that.
  • Require an API key: it’s implemented. Rotate it if it leaks.
  • Rate-limit: add a simple per-IP limit in Nginx to reduce scraping and accidental load spikes.
  • Block obvious brute force: CrowdSec fits well for internet-facing hosts.

Add a basic Nginx rate limit by editing the site config:

sudo tee /etc/nginx/conf.d/rag-ratelimit.conf > /dev/null <<'NGINX'
limit_req_zone $binary_remote_addr zone=rag_api:10m rate=5r/s;
NGINX

sudo sed -i 's/location \//location \//\n    limit_req zone=rag_api burst=20 nodelay;/' /etc/nginx/sites-available/rag-api

sudo nginx -t
sudo systemctl reload nginx

If you want automated blocking for repeated bad traffic patterns, follow Install CrowdSec on Ubuntu VPS to Block Bruteforce.

It’s usually less brittle than maintaining your own deny lists.

Connect it to a website or app (simple pattern)

Call the RAG API from your backend, not the browser. The API key is a secret.

Secrets don’t belong in client code.

Typical flow:

  1. User types a question on your site.
  2. Your backend calls https://rag.example.com/query with X-API-Key.
  3. You return the answer and, if you want, the citations.

Example Node.js (server-side) request:

const res = await fetch('https://rag.example.com/query', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': process.env.RAG_API_KEY,
  },
  body: JSON.stringify({ question: userQuestion })
});
const data = await res.json();

If you already run an OpenAI-compatible proxy for multiple apps, you can centralize auth and logging there.

HostMyCode covers that setup here: Install OpenAI-Compatible LLM Proxy on Your VPS.

Operational notes: updates, backups, and monitoring

Once people rely on this, reliability beats model tinkering.

Plan for the basics early.

  • Backups: back up Qdrant storage and your source docs (and optionally Ollama’s model cache).
  • Updates: update container images regularly, but avoid blind auto-updates without a rollback path.
  • Monitoring: watch disk, RAM, and load average. Ingestion jobs can pin CPU for long stretches.

For a clean backup routine around Docker volumes, restic plus Compose-aware hooks works well. This guide maps directly: Docker Compose Backups With Restic on a VPS.

For resource monitoring, Netdata is quick to deploy and easy to interpret. See Install Netdata on Ubuntu VPS for Real-Time Monitoring.

Honest limitations (so you don’t blame the wrong component)

  • CPU-only chat is slower: fine for internal tools, painful for high-traffic public widgets.
  • RAG doesn’t fix bad docs: stale, inconsistent, or wrong content still produces wrong answers.
  • Chunking is a big deal: the same corpus can feel sharp or useless depending on chunk size and overlap.
  • Security is your job: a private AI endpoint is still an endpoint. Rate-limit, log, and keep secrets off the client.

If you want RAG with Qdrant and Ollama to stay private and predictable, run it on infrastructure you control. A HostMyCode VPS is a clean fit for this stack, and managed VPS hosting helps if you’d rather have someone else handle baseline maintenance while you focus on the app.

FAQ: RAG with Qdrant and Ollama

Can I expose Qdrant directly to my app?

You can, but it’s rarely the right default.

Keep Qdrant on a private network and expose a narrow API that enforces auth, rate limits, and logging.

How many documents can a single VPS handle?

It depends on chunk count and vector size.

A typical 8 vCPU / 16 GB VPS can comfortably handle tens to hundreds of thousands of chunks for many small-team workloads, as long as disk is sized correctly.

Should I store PDFs directly?

Store extracted text you trust.

If you must ingest PDFs, extract text first and sanity-check it. Poor extraction hurts retrieval and leads to wrong answers.

How do I rotate the API key?

Change API_KEY in /opt/rag/.env, then restart the API container:

cd /opt/rag
sed -i "s/^API_KEY=.*/API_KEY=$(openssl rand -hex 24)/" .env
docker compose up -d

Summary: a private semantic search stack you can operate

You now have Qdrant and Ollama running on one VPS, plus a small API that handles ingestion and questions.

That’s enough for internal support search, a product documentation assistant, or any feature that needs “search by meaning” without sending data off-site.

If you want it to hold up under real use—backups, monitoring, and sane security defaults—start on a properly sized HostMyCode VPS.

Move to dedicated servers if you outgrow CPU-only inference.

Build RAG With Qdrant and Ollama on One VPS | HostMyCode