Skip to main content

6.12 Deployment & DevOps

6.12 Deployment & DevOps

Dieses Kapitel beschreibt die Deployment-Strategien des KI-CRM: den Entwicklungs-Stack auf Pop!_OS, die Synology-Produktivumgebung, die portable Variante für Endkunden und die zugehörigen .env-Schemata. Ziel ist Reproduzierbarkeit ohne manuelle Sonderschritte.


1. Drei Deployment-Varianten

VarianteZielReverse ProxyStatus
A) Dev-StackPop!_OS Server (vitruvian@pop-os)NPM internProduktiv für Entwicklung
B) Synology (intern)DS923+ (capcalc.kistudent.synology.me)Synology DSM Reverse ProxyProduktiv für Exista AG
C) KundeKunden-ServerCaddy (auto-LE)Roadmap

2. Verzeichnis-Konvention

# Pop!_OS Entwicklung
~/0_docker/7000_progstudio/ki-crm/
├── docker-compose.yml
├── .env
├── frontend/
├── backend/
├── nginx/
└── migrations/

# Synology Produktion
~/0_docker/8090_ki-crm/
├── docker-compose.yml
├── .env                  ← separat, eigene Secrets
├── frontend/dist/        ← pre-built, NICHT auf Synology bauen
├── backend/
├── nginx/
└── migrations/

# Kundenpaket
ki-crm-distribution/
├── docker-compose.yml
├── .env.example
├── frontend/dist/
├── backend/
├── nginx/
├── migrations/
├── Caddyfile
└── INSTALL.md

3. Variante A: Dev-Stack

3.1 docker-compose.yml (Auszug)

services:
  crm_nginx:
    image: nginx:alpine
    container_name: crm_nginx
    ports:
      - "8090:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./frontend/dist:/usr/share/nginx/html:ro
    depends_on: [backend]
    restart: unless-stopped

  backend:
    build: ./backend
    container_name: crm_backend
    env_file: .env
    depends_on: [crm_mariadb, crm_redis]
    restart: unless-stopped

  crm_mariadb:
    image: mariadb:10.11
    container_name: crm_mariadb
    environment:
      MARIADB_ROOT_PASSWORD: ${MARIADB_ROOT_PASSWORD}
      MARIADB_DATABASE:     ${DB_NAME}
      MARIADB_USER:         ${DB_USER}
      MARIADB_PASSWORD:     ${DB_PASSWORD}
    volumes:
      - ./data/mariadb:/var/lib/mysql
    restart: unless-stopped

  crm_redis:
    image: redis:7-alpine
    container_name: crm_redis
    restart: unless-stopped

3.2 .env (Dev)

# --- Datenbank ---
DB_NAME=crm_semitron
DB_USER=crm_user
DB_PASSWORD=Root2026!
MARIADB_ROOT_PASSWORD=...

# --- Auth ---
JWT_SECRET=ein-langes-zufaelliges-secret
SESSION_SECRET=...

# --- KI ---
OLLAMA_URL=http://host.docker.internal:11434
ANTHROPIC_API_KEY=sk-ant-api03-...
DEFAULT_PROVIDER=ollama

# --- Mail ---
SMTP_HOST=smtp.example.ch
SMTP_PORT=587
SMTP_USER=...
SMTP_PASSWORD=...
SMTP_FROM="KI-CRM <crm@exista.ch>"

# --- Schnittstellen ---
SEARXNG_URL=http://192.168.0.82:8888
WHISPER_URL=http://192.168.0.16:8085/v1/audio/transcriptions
LOCAL_API_KEY=...
ZEFIX_BASE=https://www.zefix.admin.ch/ZefixPublicREST/api/v1

# --- Sonstiges ---
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug

3.3 Start & Stopp

cd ~/0_docker/7000_progstudio/ki-crm
docker compose up -d
docker compose logs -f backend
docker compose down

4. Variante B: Synology Produktion

4.1 Synology-spezifische Eigenheiten

  • SSH-Port: 1111 (nicht 22)
  • SSH-User: abiltec
  • docker-Befehl im sudo-Kontext: sudo /usr/local/bin/docker
  • Container Manager überschreibt Volume-Mappings beim "Edit" – Re-Create-Workflow daher Pflicht
  • Shared Folders müssen vorab in DSM-UI angelegt werden, nicht via CLI
  • Synology-Reverse-Proxy macht SSL-Termination + Let's Encrypt

4.2 Deploy-Workflow

#!/bin/bash
# deploy.sh – Pop!_OS → Synology
set -e

PROJEKT_DIR=~/0_docker/7000_progstudio/ki-crm
SYNO_USER=abiltec
SYNO_HOST=192.168.0.82
SYNO_PORT=1111
SYNO_DIR=/volume1/docker/8090_ki-crm

# 1) Frontend auf Pop!_OS bauen
cd "$PROJEKT_DIR/frontend"
npm run build

# 2) Verzeichnisstruktur paketieren (KEIN node_modules!)
cd "$PROJEKT_DIR"
tar --exclude='node_modules' \
    --exclude='.git' \
    --exclude='data' \
    --exclude='.env' \
    -czf /tmp/ki-crm-deploy.tar.gz .

# 3) Per SCP nach Synology übertragen
scp -P $SYNO_PORT /tmp/ki-crm-deploy.tar.gz $SYNO_USER@$SYNO_HOST:/tmp/

# 4) Auf Synology entpacken & deployen
ssh -p $SYNO_PORT $SYNO_USER@$SYNO_HOST <<'EOF'
  set -e
  cd /volume1/docker/8090_ki-crm
  tar -xzf /tmp/ki-crm-deploy.tar.gz
  # .env bleibt unangetastet (existiert auf Synology separat)
  sudo /usr/local/bin/docker compose --env-file ./.env down
  sudo /usr/local/bin/docker compose --env-file ./.env up -d
  rm /tmp/ki-crm-deploy.tar.gz
EOF

echo "Deploy abgeschlossen."

4.3 Wichtige Konventionen

  • tar + scp statt rsync (rsync auf Synology hat sich als unzuverlässig erwiesen)
  • --env-file immer angeben, sonst lädt Compose die .env nicht zuverlässig
  • Pre-built dist/: das Frontend wird auf Pop!_OS gebaut; das fertige dist/ kommt nur als statische Dateien auf die Synology
  • Migrations: Backend prüft beim Start, ob Migrations ausstehen, und führt sie idempotent aus

4.4 nginx-Konfiguration

server {
  listen 80;
  server_name _;

  client_max_body_size 50m;

  # Static frontend
  root /usr/share/nginx/html;
  index index.html;

  # API
  location /api/ {
    proxy_pass http://backend:3000/api/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_read_timeout 600s;
    proxy_send_timeout 600s;
  }

  # Local API (für OpenClaw)
  location /local-api/ {
    allow 192.168.0.0/16;
    allow 172.16.0.0/12;
    deny all;
    proxy_pass http://backend:3000/local-api/;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_read_timeout 600s;
  }

  # Static fallback (Vue Router History Mode)
  location / {
    try_files $uri /index.html;
  }

  # Security Headers
  add_header X-Frame-Options "SAMEORIGIN" always;
  add_header X-Content-Type-Options "nosniff" always;
  add_header Referrer-Policy "no-referrer-when-downgrade" always;
}

5. Variante C: Kunden-Deployment (Roadmap)

5.1 Konzept

Das KI-CRM soll bei einem Endkunden mit minimalem Aufwand installierbar sein – idealerweise:

  1. Kunde lädt das Distributions-Archiv
  2. Kopiert .env.example nach .env, trägt seine Domain ein
  3. Startet docker compose up -d
  4. Domain zeigt auf Server, Caddy holt automatisch ein Let's-Encrypt-Zertifikat
  5. System läuft mit HTTPS

5.2 Caddyfile

{$DOMAIN} {
  encode gzip
  reverse_proxy /api/* backend:3000
  reverse_proxy /local-api/* backend:3000 {
    @internalOnly remote_ip 192.168.0.0/16 172.16.0.0/12 10.0.0.0/8
    handle @internalOnly {
      reverse_proxy backend:3000
    }
    respond "Forbidden" 403
  }
  root * /srv
  try_files {path} /index.html
  file_server
}

5.3 .env.example

# --- BASIS ---
DOMAIN=crm.example.ch              # Eigene Domain hier
ADMIN_EMAIL=admin@example.ch

# --- DB ---
DB_NAME=crm
DB_USER=crm
DB_PASSWORD=hier-langes-zufaelliges-passwort

# --- AUTH ---
JWT_SECRET=hier-mindestens-64-zeichen
SESSION_SECRET=hier-mindestens-64-zeichen

# --- KI ---
# Optional: Eigene Ollama-Instanz, sonst läuft das CRM ohne KI
OLLAMA_URL=
# Optional: Anthropic-Key, sonst läuft das CRM ohne Cloud-KI
ANTHROPIC_API_KEY=
DEFAULT_PROVIDER=ollama

# --- MAIL ---
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=

# --- SCHNITTSTELLEN ---
SEARXNG_URL=
WHISPER_URL=
LOCAL_API_KEY=hier-langes-zufaelliges-secret-fuer-die-local-api

# --- SONSTIGES ---
NODE_ENV=production
PORT=3000
LOG_LEVEL=info

6. Migrations-Lauf beim Start

Das Backend führt beim Container-Start einen Migrations-Lauf aus:

// server.js (Auszug)
const { runMigrations } = require('./migrations/runner')

async function startup() {
  await sequelize.authenticate()
  await runMigrations()           // alle ausstehenden .sql ausführen
  await initialSeed()              // optional: Standard-Daten anlegen
  app.listen(process.env.PORT || 3000)
}

startup().catch((e) => {
  logger.error('Fatal startup error', { msg: e.message })
  process.exit(1)
})

Die Migrations sind idempotent (siehe Kapitel 6.4) – mehrfache Container-Starts richten keinen Schaden an.

7. Daten-Persistenz

VolumeInhaltBackup?
./data/mariadbDB-DateienJa, mysqldump + Restic
./uploadsHochgeladene PDFs, BilderJa, Restic
./logsBackend-LogsRotation lokal, kein Off-Site
./data/redisCacheNein (regenerierbar)

8. Reverse-Proxy: Synology DSM

  1. DSM → Control Panel → Login Portal → Advanced → Reverse Proxy
  2. Neue Regel: capcalc.kistudent.synology.me → http://127.0.0.1:8090
  3. HTTPS-Settings: Synology bezieht das Let's-Encrypt-Zertifikat automatisch
  4. Custom Headers: Websocket-Support aktivieren (Upgrade, Connection)
  5. Im Synology-Firewall Port 443 und 80 von aussen zulassen (in Router weiterleiten)

9. Wartung & Monitoring

AufgabeFrequenzTool
Container Healthcheck1 minUptime Kuma
DB-BackupnächtlichCron-Job in Backend-Container
Restic-SnapshotnächtlichCron auf Host
Disk-Space-Check1 hSynology-Notifications
Log-Rotationtäglichwinston-daily-rotate-file
Update-Check Container-ImagesmonatlichManuelles Review von Releases

10. Rollback-Strategie

  1. Vor jedem Deploy: git tag deploy-YYYY-MM-DD-HHmm
  2. Vorheriges Image bleibt im Docker-Cache, kann sofort wieder gestartet werden
  3. DB-Migrationen mit IF NOT EXISTS sind nicht-destruktiv – ein Rollback der Anwendung läuft mit der "neueren" DB weiter
  4. Datenrollback (z.B. wegen Datenkorruption) via Restic-Snapshot, RTO ≤ 4 h

11. Lessons aus dem Deployment

  • Synology Container Manager ist okay für einfache Stacks, aber bei Volume-Updates ist ein vollständiger Re-Create der saubere Weg. "Edit" überschreibt manchmal Mappings stillschweigend.
  • Pre-built dist/ ist die richtige Entscheidung: Synology hätte für einen vollwertigen Node-Build genug Power, aber die Tooling-Reibung (npm-Versionen, Compiler) ist unnötig.
  • Eine separate .env pro Umgebung verhindert peinliche Vorfälle ("warum schreibt die Dev-Instanz in die Produktiv-DB"). Diese Regel ist unverhandelbar.
  • Idempotente Migrations sind unbezahlbar: Hotfixes können in beliebiger Reihenfolge ausgerollt werden, ohne dass Schema-Konflikte entstehen.
  • Die Variante C (Kunden-Deployment) ist heute noch konzeptionell, aber die Architektur lässt sie zu – die .env.example, das Caddyfile und die Migrations-Mechanik sind die Bausteine, die in den Sprints S4/S5 bewusst vorgehalten wurden.

Folgekapitel: 6.13 Sicherheit | 6.14 Probleme & Lösungen