Your RAG stack works fine until the ingestion job tries to embed thirty thousand documents in one night. The embeddings library you started with — calling out to the OpenAI embeddings API from inside the ingestion worker — runs out of rate limit at ten thousand requests, costs more per month than the underlying VM, and locks you into a vendor for the most expensive part of your inference path. The chat side already runs through a separate LLM proxy; the embeddings side is still hitting a paid API directly. Worse: the embedding model the OpenAI API exposes today is not necessarily the one you’ll want next quarter, and changing it forces a re-embed of the entire corpus.
What’s happening
Text Embeddings Inference (TEI) is Hugging Face’s high-performance server for embedding models — same role as vLLM but for the embedding side of the inference path. It speaks an OpenAI-compatible /v1/embeddings endpoint, supports the BGE family (bge-large-en-v1.5, bge-m3), the E5 family (e5-large-v2, multilingual-e5-large), the Nomic family (nomic-embed-text-v1.5), and re-ranker models (BAAI/bge-reranker-large) on a separate port. TEI works on CPU for smaller models (bge-small, gte-small) and on NVIDIA GPU for production-scale (bge-large, multilingual-e5-large, bge-m3). The host needs the NVIDIA container toolkit installed before Docker can see the GPU. The model is downloaded once on first start and cached to a persistent volume; subsequent restarts are seconds, not minutes. The /v1/embeddings endpoint should sit behind nginx with TLS and authentication — even on a private network, write down the auth header your downstream services use so the next operator does not have to reverse-engineer it. The persistent model cache lives at /var/lib/tei/data and the VM-level backup should include it (or accept the re-download cost on restore). TEI is stateless — restarting it loses no data; only the model cache matters.
How to verify
After install, the host should expose only :443 and :22:
ss -lntp | grep -E ':(80|443|8080|8081)\b'
# 0.0.0.0:443 nginx
# 127.0.0.1:8080 tei (embeddings)
# 127.0.0.1:8081 tei (reranker) -- if enabled
A health check against the embeddings endpoint:
curl -sS https://embed.example.com/health | jq .
An embeddings call:
curl -sS -H "Authorization: Bearer $TEI_AUTH_TOKEN" \
-H "Content-Type: application/json" \
https://embed.example.com/v1/embeddings \
-d '{"input":"hello","model":"BAAI/bge-large-en-v1.5"}' \
| jq '.data[0].embedding | length'
# 1024 -- bge-large outputs 1024-dim vectors
If the response returns a vector with a different dimensionality than the receiving vector store expects, the model is misnamed or your Qdrant collection / pgvector column was sized for a different model. Re-embedding is the only fix; collections are not silently resizable.
On a GPU host, confirm the model is actually on the GPU:
docker exec -it tei nvidia-smi | head -20
# Look for a python process holding ~3-4 GB of GPU memory for bge-large.
The fix
Save the script below as /root/setup-tei-ubuntu22.sh, then run it. It installs TEI on a fresh Ubuntu 22.04 VM via Docker Compose: base update, UFW (SSH + HTTP + HTTPS only), SSH hardening with root key preserved, unattended-upgrades, Docker CE + compose plugin, optional NVIDIA container toolkit (when TEI_DEVICE=gpu), the TEI container with the model name written to /opt/tei/.env with chmod 600, an optional reranker container on a second port, nginx terminating TLS with bearer-token auth checked at the edge, Let’s Encrypt via the certbot nginx plugin, and a poll loop that waits for the model to finish downloading.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 Text Embeddings Inference clean VM installer
### CPU or NVIDIA GPU (set TEI_DEVICE=gpu and have an NVIDIA-capable VM)
### Keeps root SSH key login enabled, disables SSH password login
### Bearer-token check at nginx edge
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${TEI_DOMAIN:?Set TEI_DOMAIN=embed.example.com}"
: "${TEI_EMAIL:?Set TEI_EMAIL=ops@example.com for Let's Encrypt}"
TEI_DEVICE="${TEI_DEVICE:-cpu}" # cpu | gpu
TEI_MODEL="${TEI_MODEL:-BAAI/bge-large-en-v1.5}"
TEI_RERANKER_MODEL="${TEI_RERANKER_MODEL:-}" # empty disables reranker
TEI_AUTH_TOKEN="${TEI_AUTH_TOKEN:-$(openssl rand -hex 32)}"
# Image tag selection: -1.5 line, CPU vs GPU
if [[ "${TEI_DEVICE}" == "gpu" ]]; then
TEI_IMAGE="ghcr.io/huggingface/text-embeddings-inference:1.5"
else
TEI_IMAGE="ghcr.io/huggingface/text-embeddings-inference:cpu-1.5"
fi
echo
echo "========================================"
echo "TEI Ubuntu 22.04 Setup (${TEI_DEVICE})"
echo "Model: ${TEI_MODEL}"
echo "========================================"
echo
echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade
echo "==> Installing base packages"
apt-get -y install \
vim curl wget ca-certificates gnupg2 \
chrony fail2ban unattended-upgrades \
ufw lsof tcpdump dnsutils tar gzip \
iproute2 net-tools openssl jq \
software-properties-common pciutils
echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true
echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-tei.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.max_map_count = 262144
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system
cat > /etc/security/limits.d/99-tei.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS
echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
echo "==> Hardening SSH"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
local key="$1"
local value="$2"
if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
else
echo "${key} ${value}" >> /etc/ssh/sshd_config
fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
sshd -t
systemctl restart ssh
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AUTOUPG
echo "==> Installing Docker CE"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
| gpg --dearmor -o /etc/apt/keyrings/docker.gpg
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 jammy stable" \
> /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker
if [[ "${TEI_DEVICE}" == "gpu" ]]; then
echo "==> Installing NVIDIA container toolkit"
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey \
| gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
curl -fsSL https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list \
| sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' \
> /etc/apt/sources.list.d/nvidia-container-toolkit.list
apt-get update
apt-get -y install nvidia-container-toolkit
nvidia-ctk runtime configure --runtime=docker
systemctl restart docker
fi
echo "==> Preparing /opt/tei and model cache"
mkdir -p /opt/tei /var/lib/tei/data
chmod 700 /opt/tei /var/lib/tei /var/lib/tei/data
cat > /opt/tei/.env <<ENV
TEI_IMAGE=${TEI_IMAGE}
TEI_MODEL=${TEI_MODEL}
TEI_RERANKER_MODEL=${TEI_RERANKER_MODEL}
TEI_AUTH_TOKEN=${TEI_AUTH_TOKEN}
ENV
chmod 600 /opt/tei/.env
# Compose file changes slightly between cpu and gpu mode
if [[ "${TEI_DEVICE}" == "gpu" ]]; then
cat > /opt/tei/docker-compose.yml <<'COMPOSE'
services:
tei:
image: ${TEI_IMAGE}
restart: unless-stopped
runtime: nvidia
environment:
MODEL_ID: ${TEI_MODEL}
MAX_CLIENT_BATCH_SIZE: "128"
MAX_BATCH_TOKENS: "16384"
AUTO_TRUNCATE: "true"
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
volumes:
- /var/lib/tei/data:/data
ports:
- "127.0.0.1:8080:80"
tei-reranker:
image: ${TEI_IMAGE}
restart: unless-stopped
runtime: nvidia
profiles: ["reranker"]
environment:
MODEL_ID: ${TEI_RERANKER_MODEL}
MAX_CLIENT_BATCH_SIZE: "64"
AUTO_TRUNCATE: "true"
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
volumes:
- /var/lib/tei/data:/data
ports:
- "127.0.0.1:8081:80"
COMPOSE
else
cat > /opt/tei/docker-compose.yml <<'COMPOSE'
services:
tei:
image: ${TEI_IMAGE}
restart: unless-stopped
environment:
MODEL_ID: ${TEI_MODEL}
MAX_CLIENT_BATCH_SIZE: "32"
MAX_BATCH_TOKENS: "8192"
AUTO_TRUNCATE: "true"
volumes:
- /var/lib/tei/data:/data
ports:
- "127.0.0.1:8080:80"
tei-reranker:
image: ${TEI_IMAGE}
restart: unless-stopped
profiles: ["reranker"]
environment:
MODEL_ID: ${TEI_RERANKER_MODEL}
MAX_CLIENT_BATCH_SIZE: "16"
AUTO_TRUNCATE: "true"
volumes:
- /var/lib/tei/data:/data
ports:
- "127.0.0.1:8081:80"
COMPOSE
fi
echo "==> Starting TEI"
if [[ -n "${TEI_RERANKER_MODEL}" ]]; then
docker compose --env-file /opt/tei/.env --profile reranker -f /opt/tei/docker-compose.yml up -d
else
docker compose --env-file /opt/tei/.env -f /opt/tei/docker-compose.yml up -d
fi
echo "==> Waiting for TEI model download + load (this may take 1-5 minutes)"
TEI_READY=0
for i in {1..300}; do
if curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/health 2>/dev/null | grep -q '200'; then
TEI_READY=1
break
fi
sleep 2
done
if [[ "${TEI_READY}" -ne 1 ]]; then
echo "TEI did not become ready"
docker compose -f /opt/tei/docker-compose.yml logs --tail=200 tei || true
exit 1
fi
echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx
cat > /etc/nginx/sites-available/tei <<NGINX
map \$http_authorization \$tei_authorized {
default 0;
"Bearer ${TEI_AUTH_TOKEN}" 1;
}
upstream tei_embed { server 127.0.0.1:8080; keepalive 16; }
upstream tei_rerank { server 127.0.0.1:8081; keepalive 16; }
server {
listen 80;
server_name ${TEI_DOMAIN};
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl http2;
server_name ${TEI_DOMAIN};
client_max_body_size 50M;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff always;
add_header X-Frame-Options DENY always;
# /health is public; nothing else is
location = /health {
proxy_pass http://tei_embed/health;
}
location /rerank/ {
if (\$tei_authorized = 0) { return 401; }
rewrite ^/rerank/(.*)\$ /\$1 break;
proxy_set_header Host \$host;
proxy_set_header Authorization "";
proxy_pass http://tei_rerank;
}
location / {
if (\$tei_authorized = 0) { return 401; }
proxy_set_header Host \$host;
proxy_set_header Authorization "";
proxy_pass http://tei_embed;
}
}
NGINX
ln -sf /etc/nginx/sites-available/tei /etc/nginx/sites-enabled/tei
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx
echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
-m "${TEI_EMAIL}" -d "${TEI_DOMAIN}" --redirect
systemctl enable --now certbot.timer
echo "==> Final package update"
apt-get -y upgrade
echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|8080|8081)\b' || true
echo
echo "Containers:"
docker compose -f /opt/tei/docker-compose.yml ps
echo
echo "Health check:"
curl -sS https://${TEI_DOMAIN}/health || true
echo
echo "Auth check (expect 401):"
curl -sS -o /dev/null -w '%{http_code}\n' "https://${TEI_DOMAIN}/v1/embeddings" || true
echo
echo "Bearer token: ${TEI_AUTH_TOKEN}"
echo "Model: ${TEI_MODEL}"
echo "Reranker: ${TEI_RERANKER_MODEL:-disabled}"
echo
echo "Downstream config (LiteLLM, AnythingLLM, custom code):"
echo " base_url = https://${TEI_DOMAIN}/v1"
echo " api_key = ${TEI_AUTH_TOKEN}"
echo " model = ${TEI_MODEL}"
echo
echo "Vector store dimensionality reminder:"
echo " bge-large-en-v1.5 -> 1024"
echo " bge-m3 -> 1024"
echo " multilingual-e5-large -> 1024"
echo " bge-small-en-v1.5 -> 384"
echo " nomic-embed-text-v1.5 -> 768"
echo " Re-creating a Qdrant collection with the wrong dim breaks every existing point silently."
Make it executable and run it:
chmod 700 /root/setup-tei-ubuntu22.sh
TEI_DOMAIN=embed.example.com \
TEI_EMAIL=ops@example.com \
TEI_DEVICE=gpu \
TEI_MODEL=BAAI/bge-large-en-v1.5 \
TEI_RERANKER_MODEL=BAAI/bge-reranker-large \
/root/setup-tei-ubuntu22.sh
For CPU-only operation (smaller models, throttled throughput), set TEI_DEVICE=cpu and TEI_MODEL=BAAI/bge-small-en-v1.5. Downstream services point at https://embed.example.com/v1 with the printed bearer token as the API key — that is the OpenAI-compatible shape AnythingLLM, LiteLLM, langchain, and most other RAG stacks already understand. Switching embedding model in the future is a config change on this host plus a re-embed of the corpus; downstream code does not need to change. The model cache at /var/lib/tei/data should be in your VM-level backup or you accept the re-download cost on restore.
Run this embedding service on Stack Harbor’s managed cloud compute with GPU patching, monitoring, and Sev-1 escalation: Cloud compute. To plan capacity around your RAG corpus volume and ingestion windows, start the conversation.