Skip to content

Deploying Khoj as a self-hosted personal AI assistant on Ubuntu 22.04

Stand up a hardened Khoj instance on Ubuntu 22.04 via Docker — Postgres + pgvector backend, Notion / GitHub / Markdown indexers, LiteLLM-routed chat models, nginx + Let's Encrypt.

A handful of senior engineers and PMs want an AI assistant connected to “everything I have access to” — their Notion workspace, their Markdown notes repo, the GitHub repos they’re subscribed to, maybe the corporate Confluence read-only. They’ve been pasting documents into a public chat tool, which is the security tomorrow that everyone is going to have to clean up. You need a self-hosted assistant that indexes their personal corpora (each siloed to that user), runs chat through whatever LLM you already route through your LiteLLM proxy, and stays out of the path of the team’s central RAG stack. Khoj is the right shape for that.

What’s happening

Khoj is an open-source personal AI assistant that supports plug-in indexers for Notion, GitHub, plain-text/Markdown directories, PDFs, and a handful of other sources. Each user account has its own corpus; cross-user retrieval is not enabled. The backend uses Postgres with the pgvector extension for vector storage — no separate vector database to operate. Khoj can call out to local LLMs (Ollama, LocalAI, LiteLLM) or proprietary APIs; routing chat through your LiteLLM proxy gives you central budgets and audit logs even though each user is a workspace of one. The Khoj container needs the Postgres URL, an OPENAI_API_BASE pointing at the proxy, and an OPENAI_API_KEY that is a virtual key on the proxy. The web client (Settings → “Source Plugins”) accepts API tokens for Notion and GitHub on a per-user basis — never the global integration tokens, just the user’s own. Index sync is on a cron the user controls. The desktop / mobile clients all read from the same backend. Multi-user mode is enabled via Django admin (Khoj is built on Django) on first boot; the default is single-user, which is fine for the very small team this is meant to serve. Telemetry is off-by-default in self-host but worth confirming with KHOJ_TELEMETRY_DISABLE=true. The Postgres database is the only persistent state worth backing up; the embedding cache rebuilds from source on demand.

How to verify

After install, the host should expose only :443 and :22:

ss -lntp | grep -E ':(80|443|42110|5432)\b'
# 0.0.0.0:443  nginx
# 127.0.0.1:42110 khoj (via compose)

A health check:

curl -sS https://khoj.example.com/api/health
# {"status": "ok"}

The chat endpoint requires authentication; an unauthenticated call returns 401:

curl -sS -o /dev/null -w '%{http_code}\n' "https://khoj.example.com/api/chat?q=ping"
# 401

Once a user signs in (the first sign-in becomes the admin), an authenticated call returns a streamed response. Confirm the chat is being routed through your LiteLLM proxy by tailing the proxy logs:

ssh ops@llm.example.com 'docker logs litellm 2>&1 | grep -i "khoj"'

If chat appears to work but the response feels uncharacteristically short or generic for the model, the proxy bypassed and the backend silently fell back to a default. Look for OPENAI_API_BASE in docker exec khoj env and confirm it matches your proxy.

The fix

Save the script below as /root/setup-khoj-ubuntu22.sh, then run it. It installs Khoj 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, Postgres 16 with pgvector kept on the internal compose network, Khoj container with secret_key and admin credentials in /opt/khoj/.env (mode 600), telemetry disabled, chat routing pointed at the LiteLLM proxy, nginx terminating TLS, Let’s Encrypt via the certbot nginx plugin, and a poll loop that waits for the API.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Khoj clean VM installer
### Self-hosted personal AI assistant, Postgres + pgvector backend
### Chat routed through LiteLLM proxy (or any OpenAI-compatible endpoint)
### Telemetry off
### Keeps root SSH key login enabled, disables SSH password login

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${KHOJ_DOMAIN:?Set KHOJ_DOMAIN=khoj.example.com}"
: "${KHOJ_EMAIL:?Set KHOJ_EMAIL=ops@example.com for Let's Encrypt}"
: "${KHOJ_CHAT_API_BASE:?Set KHOJ_CHAT_API_BASE=https://llm.example.com/v1 (your LiteLLM proxy)}"
: "${KHOJ_CHAT_API_KEY:?Set KHOJ_CHAT_API_KEY=sk-khoj-... (a LiteLLM virtual key dedicated to Khoj)}"
KHOJ_VERSION="${KHOJ_VERSION:-1.32.4}"
KHOJ_ADMIN_EMAIL="${KHOJ_ADMIN_EMAIL:-${KHOJ_EMAIL}}"
KHOJ_ADMIN_PASSWORD="${KHOJ_ADMIN_PASSWORD:-$(openssl rand -base64 18)}"
KHOJ_DJANGO_SECRET="${KHOJ_DJANGO_SECRET:-$(openssl rand -hex 48)}"
KHOJ_PG_PASSWORD="${KHOJ_PG_PASSWORD:-$(openssl rand -hex 24)}"
KHOJ_CHAT_MODEL="${KHOJ_CHAT_MODEL:-claude-sonnet-4}"
KHOJ_EMBED_MODEL="${KHOJ_EMBED_MODEL:-BAAI/bge-large-en-v1.5}"

echo "========================================"
echo "Khoj Ubuntu 22.04 Setup"
echo "========================================"

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

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

systemctl enable --now chrony
timedatectl set-ntp true

cat > /etc/sysctl.d/99-khoj.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-khoj.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
LIMITS

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

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 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

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

mkdir -p /opt/khoj /var/lib/khoj/state
chmod 700 /opt/khoj /var/lib/khoj /var/lib/khoj/state

cat > /opt/khoj/.env <<ENV
KHOJ_VERSION=${KHOJ_VERSION}
KHOJ_DOMAIN=${KHOJ_DOMAIN}
KHOJ_DJANGO_SECRET=${KHOJ_DJANGO_SECRET}
KHOJ_ADMIN_EMAIL=${KHOJ_ADMIN_EMAIL}
KHOJ_ADMIN_PASSWORD=${KHOJ_ADMIN_PASSWORD}
KHOJ_PG_PASSWORD=${KHOJ_PG_PASSWORD}
KHOJ_CHAT_API_BASE=${KHOJ_CHAT_API_BASE}
KHOJ_CHAT_API_KEY=${KHOJ_CHAT_API_KEY}
KHOJ_CHAT_MODEL=${KHOJ_CHAT_MODEL}
KHOJ_EMBED_MODEL=${KHOJ_EMBED_MODEL}
ENV
chmod 600 /opt/khoj/.env

cat > /opt/khoj/docker-compose.yml <<'COMPOSE'
services:
  postgres:
    image: ankane/pgvector:v0.5.1
    restart: unless-stopped
    environment:
      POSTGRES_USER: khoj
      POSTGRES_PASSWORD: ${KHOJ_PG_PASSWORD}
      POSTGRES_DB: khoj
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U khoj -d khoj"]
      interval: 30s
      timeout: 5s
      retries: 5
      start_period: 20s

  khoj:
    image: ghcr.io/khoj-ai/khoj:${KHOJ_VERSION}
    restart: unless-stopped
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      KHOJ_DJANGO_SECRET_KEY: ${KHOJ_DJANGO_SECRET}
      KHOJ_ADMIN_EMAIL: ${KHOJ_ADMIN_EMAIL}
      KHOJ_ADMIN_PASSWORD: ${KHOJ_ADMIN_PASSWORD}
      KHOJ_DEBUG: "false"
      KHOJ_TELEMETRY_DISABLE: "true"
      KHOJ_ALLOWED_HOSTS: ${KHOJ_DOMAIN}
      KHOJ_DOMAIN: ${KHOJ_DOMAIN}
      KHOJ_NO_HTTPS: "false"
      POSTGRES_HOST: postgres
      POSTGRES_PORT: "5432"
      POSTGRES_DB: khoj
      POSTGRES_USER: khoj
      POSTGRES_PASSWORD: ${KHOJ_PG_PASSWORD}
      OPENAI_API_BASE: ${KHOJ_CHAT_API_BASE}
      OPENAI_API_KEY: ${KHOJ_CHAT_API_KEY}
      KHOJ_DEFAULT_CHAT_MODEL: ${KHOJ_CHAT_MODEL}
      KHOJ_DEFAULT_EMBEDDING_MODEL: ${KHOJ_EMBED_MODEL}
    volumes:
      - /var/lib/khoj/state:/root/.khoj
    ports:
      - "127.0.0.1:42110:42110"
    ulimits:
      nofile:
        soft: 64000
        hard: 64000

volumes:
  pgdata:
    driver: local
COMPOSE

docker compose --env-file /opt/khoj/.env -f /opt/khoj/docker-compose.yml up -d

echo "==> Waiting for Khoj on 127.0.0.1:42110"
KHOJ_READY=0
for i in {1..180}; do
  if curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:42110/api/health 2>/dev/null | grep -q '200'; then
    KHOJ_READY=1
    break
  fi
  sleep 2
done

if [[ "${KHOJ_READY}" -ne 1 ]]; then
  docker compose -f /opt/khoj/docker-compose.yml logs --tail=200 khoj || true
  exit 1
fi

apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/khoj <<NGINX
upstream khoj_backend {
    server 127.0.0.1:42110;
    keepalive 32;
}

server {
    listen 80;
    server_name ${KHOJ_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name ${KHOJ_DOMAIN};

    client_max_body_size 200M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location / {
        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_http_version 1.1;
        proxy_buffering off;
        proxy_pass http://khoj_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/khoj /etc/nginx/sites-enabled/khoj
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx

certbot --nginx --non-interactive --agree-tos \
  -m "${KHOJ_EMAIL}" -d "${KHOJ_DOMAIN}" --redirect

systemctl enable --now certbot.timer

apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Web UI: https://${KHOJ_DOMAIN}/"
echo "Admin:  https://${KHOJ_DOMAIN}/server/admin/"
echo "Admin email:    ${KHOJ_ADMIN_EMAIL}"
echo "Admin password: ${KHOJ_ADMIN_PASSWORD}"
echo
echo "Chat is routed through:"
echo "  base = ${KHOJ_CHAT_API_BASE}"
echo "  key  = ${KHOJ_CHAT_API_KEY:0:8}..."
echo "  model = ${KHOJ_CHAT_MODEL}"
echo
echo "First steps:"
echo "1. Open the URL and sign in with the admin email/password."
echo "2. Add additional users via the /server/admin/ Django console."
echo "3. Each user goes to Settings -> Source Plugins to wire up their Notion / GitHub."
echo "4. Each user sees only their own indexed content. Cross-user retrieval is disabled by design."
echo
echo "Backup target: the Postgres database. /var/lib/khoj/state holds rebuildable cache only."

Make it executable and run it:

chmod 700 /root/setup-khoj-ubuntu22.sh
KHOJ_DOMAIN=khoj.example.com \
KHOJ_EMAIL=ops@example.com \
KHOJ_CHAT_API_BASE=https://llm.example.com/v1 \
KHOJ_CHAT_API_KEY=sk-khoj-virtualkey-from-litellm-ui \
KHOJ_CHAT_MODEL=claude-sonnet-4 \
/root/setup-khoj-ubuntu22.sh

The first sign-in becomes the admin. Add additional users through /server/admin/. Each user adds their own Notion API token, their own GitHub PAT, their own Markdown directory mount under Settings → Source Plugins; the corpora are siloed at the user-row level in Postgres. Chat is routed through your LiteLLM proxy, which means: one virtual key per user if you want per-user budgets, or one shared “khoj” virtual key if the small team is fine with a single budget bucket. Telemetry is disabled by KHOJ_TELEMETRY_DISABLE=true; do not let any user toggle it back on through the UI. Postgres is the only target for backup — the local state directory caches embeddings that can be rebuilt from source on demand.

Run this assistant on Stack Harbor’s managed cloud compute with patching, monitoring, and Sev-1 escalation in place: Cloud compute. For per-user budget rotation and the onboarding/offboarding integration that revokes a leaving user’s Notion + GitHub tokens at the same time as their access, see Managed Cloud Ops.