Skip to content

deployment

khanhthanhdev edited this page Jun 2, 2026 · 1 revision

Deployment

AI Knowledge Cloud runs on a single VPS using Docker Compose with seven services. The build process intentionally separates image creation from Next.js compilation to support cacheComponents which requires a live database at build time.

Architecture

flowchart TD
    Internet -->|HTTPS| CF[Cloudflare]
    CF -->|HTTP| Caddy[:80 Caddy Reverse Proxy]
    Caddy --> App[:5175 Next.js App]
    Caddy --> Inngest[:8288 Inngest Dashboard]
    Caddy --> QD[:6333 Qdrant]
    Caddy --> PG[:3000 PostgREST]
    Caddy --> INF[:7997 Infinity Embeddings]
    App --> PG_DB[(PostgreSQL)]
    App --> QD
    App --> Inngest
    App --> INF
    Inngest --> App
    PG --> PG_DB
Loading

Services

Service Image Port Purpose
postgres postgres:17-alpine 5432 Primary database with citext and pg_trgm extensions
qdrant qdrant/qdrant:v1.16.1 6333 Vector database for hybrid search and semantic cache
infinity michaelf34/infinity:latest-cpu 7997 Local embedding server (replaces cloud embedding APIs)
inngest inngest/inngest 8288 Background job runner (localhost only)
app aikc-local-app 5175 Next.js application server
postgrest postgrest/postgrest 3000 REST API layer over PostgreSQL
caddy caddy:2-alpine 80 Reverse proxy with security headers

Init Services (run once)

Service Purpose
migrate Runs prisma db push --skip-generate
build Runs next build against live database
qdrant-setup Initializes Qdrant collections (profile: setup)
pg-tools Database utilities (profile: ops)

Build Process

The Dockerfile uses a two-stage build. Critically, next build does not run during docker build because cacheComponents requires generateStaticParams to query the live database.

flowchart LR
    A[deps stage] -->|Install packages| B[app stage]
    B -->|Copy node_modules + source| C[Image: aikc-local-app]
    C -->|compose build service| D[next build]
    D -->|.next volume| E[app service: next start]
Loading

Dockerfile Stages

Stage 1: deps

FROM oven/bun:1 AS deps
COPY package.json bun.lock ./
COPY prisma ./prisma/
RUN bun install --frozen-lockfile

Stage 2: app

FROM base AS app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN bunx prisma generate

Compose Build Sequence

  1. postgres starts and passes health check
  2. migrate runs prisma db push (depends on postgres)
  3. build runs next build (depends on migrate, shares app_next volume)
  4. app starts with next start (depends on build, mounts same app_next volume)

The app_next named volume is shared between build and app services so the compiled .next output is available to the runtime container.

Caddy Reverse Proxy

The Caddyfile (Caddyfile) configures:

Security Headers

X-Frame-Options "DENY"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "camera=(), microphone=(), geolocation=()"
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
Cross-Origin-Opener-Policy "same-origin"
Cross-Origin-Resource-Policy "same-origin"

Cloudflare Integration

  • Trusted proxies — all Cloudflare IP ranges are listed in trusted_proxies
  • IP forwarding — X-Real-IP is set from CF-Connecting-IP header
  • Host validation — requests without matching Host header (aikc.vn or www.aikc.vn) receive a 444 response
  • Auto-HTTPS disabled — Cloudflare terminates TLS; Caddy handles HTTP only

Routing

Path Target
/healthz Returns 200 (health check)
/cdn-cgi/trace Returns 200 (Cloudflare proxy check)
/inngest/* Proxied to Inngest (with Basic Auth)
/* Proxied to app:5175

Environment Variables

Required Production Variables

Variable Description
COMPOSE_SITE_URL Public site URL (e.g., https://aikc.vn)
COMPOSE_SITE_EMAIL Contact email
POSTGRES_USER Database username
POSTGRES_PASSWORD Database password
POSTGRES_DB Database name
AUTH_SECRET NextAuth session secret (32+ chars)
AUTH_GOOGLE_ID Google OAuth client ID
AUTH_GOOGLE_SECRET Google OAuth client secret
OPENAI_API_KEY OpenAI API key
GEMINI_API_KEY Google Gemini API key
QDRANT_API_KEY Qdrant API key

Optional Variables

Variable Default Description
USE_LOCAL_EMBEDDING true Use Infinity for embeddings instead of cloud APIs
INFINITY_MODEL_ID sentence-transformers/all-MiniLM-L6-v2 Embedding model
INFINITY_EMBEDDING_DIMENSIONS 384 Embedding dimensions
RAG_ENABLED true Enable RAG endpoints
PUBLISH_SUBMITTER_EMAILS true Email submitters on publish
INNGEST_EVENT_KEY local-inngest-event-key Inngest event key
INNGEST_SIGNING_KEY (default hex) Inngest signing key

The full environment is defined in the x-app-environment anchor in docker-compose.yml and applied to all services that need it.

VPS Deployment

Requirements

Requirement Minimum Recommended
OS Ubuntu 22.04 Ubuntu 24.04
CPU 2 cores 4 cores
RAM 4 GB 8 GB
Storage 40 GB SSD 80 GB SSD

Initial Setup

# Install Docker
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER

# Clone repository
git clone git@github.com:<org>/<repo>.git /srv/stukit/app

# Configure environment
cp .env.production.example /srv/stukit/shared/.env.production
# Edit /srv/stukit/shared/.env.production with production values

# Deploy
docker compose --env-file /srv/stukit/shared/.env.production up -d --build

Deploy Script

#!/usr/bin/env bash
set -Eeuo pipefail
APP_DIR="/srv/stukit/app"
ENV_FILE="/srv/stukit/shared/.env.production"
cd "$APP_DIR"
git fetch origin && git checkout main && git pull --ff-only origin main
docker compose --env-file "$ENV_FILE" up -d --build --remove-orphans
docker image prune -f

CI/CD with GitHub Actions

name: Deploy to VPS
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: appleboy/ssh-action@v1.2.0
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: cd /srv/stukit && ./deploy.sh

Backup & Restore

Backup Script

scripts/backup-postgres.sh performs:

  1. pg_dump to local file
  2. gzip compression
  3. Upload to Google Drive (via gupload)
  4. Cleanup of local backups older than 7 days

Schedule with cron: 0 2 * * * /srv/stukit/app/scripts/backup-postgres.sh

Restore Script

scripts/restore-postgres.sh supports:

  • --list — list local backups
  • --list-drive — list Google Drive backups
  • --restore <YYYYMMDD_HHMMSS> — restore from local backup
  • --restore-drive <filename> — download and restore from Google Drive

The restore process drops and recreates the database before importing.

Persistent Volumes

Volume Service Purpose
postgres_data postgres Database files
qdrant_data qdrant Vector index storage
infinity_cache infinity Model cache
app_next build → app Compiled Next.js output
app_next_cache app ISR/PPR cache between restarts
caddy_data caddy TLS certificates (unused with Cloudflare)
caddy_config caddy Caddy configuration

Troubleshooting

Issue Command Fix
Container won't start docker compose logs <service> Check logs for errors
Database connection failed docker compose exec postgres psql -U aikc Verify credentials
Build OOM docker stats Increase VPS RAM or swap
Stale .next output docker compose down && docker volume rm app_next Force rebuild
Qdrant schema drift bun run qdrant:drift Check collection alignment

Key Source Files

File Purpose
Dockerfile Two-stage build (deps → app)
docker-compose.yml All service definitions and environment
Caddyfile Reverse proxy and security headers
scripts/backup-postgres.sh Database backup to Google Drive
scripts/restore-postgres.sh Database restore from local/Drive
scripts/bootstrap-postgres.sh Initial database setup
scripts/setup-qdrant.ts Qdrant collection initialization
docs/DEPLOYMENT.md Extended deployment documentation
DEPLOYMENT.md Quick deployment reference

Related Pages

Clone this wiki locally