# 🐳 Docker Deployment Guide for Proxmox

Complete guide to deploy Memento on Proxmox using Docker Compose.

## 📋 Prerequisites

### On Your Proxmox Host:
- Proxmox VE 7.x or 8.x
- Docker and Docker Compose installed
- At least 2GB RAM available (4GB+ recommended for AI features)
- 10GB disk space available

### Optional for AI Features:
- **For OpenAI**: Valid API key
- **For Ollama (Local AI)**: 8GB+ RAM, 4+ CPU cores recommended

## 🚀 Quick Start

### 1. Prepare Environment Files

Create a `.env` file in the `keep-notes` directory:

```bash
cd /path/to/keep-notes
cat > .env << 'EOF'
# Required: Generate a random secret
NEXTAUTH_SECRET=$(openssl rand -base64 32)
NEXTAUTH_URL=http://your-domain.com:3000

# Optional: OpenAI API Key
# OPENAI_API_KEY=sk-your-key-here

# Optional: Ollama Configuration (if using local AI)
# OLLAMA_BASE_URL=http://ollama:11434
# OLLAMA_MODEL=granite4:latest

# Optional: Custom Session Max Age (in seconds)
NEXTAUTH_SESSION_MAX_AGE=604800
EOF
```

### 2. Build and Start Containers

```bash
# Build the Docker image
docker compose build

# Start the application
docker compose up -d

# View logs
docker compose logs -f keep-notes
```

### 3. Access the Application

Open your browser and navigate to:
- **http://YOUR_PROXMOX_IP:3000**

## 🔧 Configuration Options

### Without Reverse Proxy (Basic)

Edit `docker-compose.yml`:
```yaml
environment:
  - NEXTAUTH_URL=http://your-ip:3000
  - NEXTAUTH_SECRET=your-random-secret
ports:
  - "3000:3000"
```

### With Nginx Reverse Proxy (Recommended)

#### 1. Create Nginx Configuration

```nginx
# /etc/nginx/conf.d/keep-notes.conf
server {
    listen 80;
    server_name notes.yourdomain.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        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;
    }

    # Max upload size for images
    client_max_body_size 10M;
}
```

#### 2. Update docker-compose.yml

```yaml
environment:
  - NEXTAUTH_URL=https://notes.yourdomain.com
```

#### 3. Restart Container

```bash
docker compose down
docker compose up -d
```

### With SSL/HTTPS (Let's Encrypt)

```bash
# Install certbot
apt install certbot python3-certbot-nginx

# Get certificate
certbot --nginx -d notes.yourdomain.com

# Auto-renewal (cron)
echo "0 0,12 * * * root certbot renew --quiet" | tee /etc/cron.d/certbot-renew
```

## 🤖 AI Features Setup

### Option 1: OpenAI (Cloud)

1. Get API key from https://platform.openai.com/api-keys
2. Add to `.env`:
   ```bash
   OPENAI_API_KEY=sk-your-key-here
   ```
3. Restart: `docker compose restart`

### Option 2: Ollama (Local AI)

#### 1. Enable Ollama in docker-compose.yml

Uncomment the `ollama` service section in `docker-compose.yml`:

```yaml
ollama:
  image: ollama/ollama:latest
  container_name: keep-ollama
  restart: unless-stopped
  ports:
    - "11434:11434"
  volumes:
    - ollama-data:/root/.ollama
  networks:
    - keep-network
```

Uncomment volume:
```yaml
volumes:
  ollama-data:
    driver: local
```

#### 2. Add Environment Variables

```yaml
keep-notes:
  environment:
    - OLLAMA_BASE_URL=http://ollama:11434
    - OLLAMA_MODEL=granite4:latest
```

#### 3. Start and Pull Model

```bash
docker compose up -d
docker compose exec -it ollama ollama pull granite4
```

### Option 3: Custom OpenAI-compatible API

If you have a custom API (like LocalAI, LM Studio, etc.):

```bash
# Add to .env or docker-compose.yml
OPENAI_API_BASE_URL=http://your-api-host:port/v1
OPENAI_API_KEY=any-key-here
```

## 📊 Resource Recommendations

### Minimal Setup (Without AI)
- **CPU**: 1 core
- **RAM**: 512MB
- **Disk**: 5GB

### Recommended Setup (With OpenAI)
- **CPU**: 1-2 cores
- **RAM**: 1-2GB
- **Disk**: 10GB

### AI Setup (With Ollama)
- **CPU**: 4+ cores
- **RAM**: 8GB+
- **Disk**: 20GB+

## 🗄️ Database Backup

### Backup SQLite Database

```bash
# Create backup script
cat > /path/to/backup-keep.sh << 'EOF'
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/path/to/backups"
CONTAINER_NAME="keep-notes"

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup database
docker exec $CONTAINER_NAME \
  cp /app/prisma/dev.db /app/prisma/backup_$DATE.db

# Copy from container to host
docker cp $CONTAINER_NAME:/app/prisma/backup_$DATE.db \
  $BACKUP_DIR/keep-notes_$DATE.db

# Keep last 7 days
find $BACKUP_DIR -name "keep-notes_*.db" -mtime +7 -delete

echo "Backup completed: keep-notes_$DATE.db"
EOF

chmod +x /path/to/backup-keep.sh

# Add to crontab (daily backup at 2 AM)
crontab -e
# Add: 0 2 * * * /path/to/backup-keep.sh
```

### Restore Database

```bash
# Stop container
docker compose down

# Restore database
cp /path/to/backups/keep-notes_YYYYMMDD_HHMMSS.db \
  keep-notes/prisma/dev.db

# Start container
docker compose up -d
```

## 🔄 Updating the Application

```bash
# Pull latest changes
git pull

# Rebuild image
docker compose build

# Restart with new image
docker compose down
docker compose up -d

# Clean up old images
docker image prune -a -f
```

## 🐛 Troubleshooting

### Container Won't Start

```bash
# Check logs
docker compose logs keep-notes

# Check container status
docker compose ps

# Enter container for debugging
docker compose exec keep-notes sh
```

### Database Errors

```bash
# Fix database permissions
docker compose exec keep-notes \
  chown -R nextjs:nodejs /app/prisma

# Regenerate Prisma client
docker compose exec keep-notes \
  npx prisma generate

# Run migrations
docker compose exec keep-notes \
  npx prisma migrate deploy
```

### AI Features Not Working

```bash
# Check Ollama status
docker compose logs ollama

# Test Ollama connection
docker compose exec keep-notes \
  curl http://ollama:11434/api/tags

# Check environment variables
docker compose exec keep-notes env | grep -E "OLLAMA|OPENAI"
```

### Performance Issues

```bash
# Check resource usage
docker stats keep-notes

# Increase resources in docker-compose.yml
deploy:
  resources:
    limits:
      cpus: '4'
      memory: 4G
```

## 🔒 Security Best Practices

1. **Change NEXTAUTH_SECRET**: Never use the default value
2. **Use HTTPS**: Always use SSL in production
3. **Limit Resources**: Prevent container from using all system resources
4. **Regular Updates**: Keep Docker image and dependencies updated
5. **Backups**: Set up automated database backups
6. **Firewall**: Only expose necessary ports (3000 or reverse proxy port)

## 📱 Proxmox LXC Container Setup

### Create LXC Container (Recommended)

```bash
# In Proxmox shell
pveam available
pveam update

# Create Ubuntu 22.04 container
pct create 999 local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst \
  --hostname keep-notes \
  --storage local-lvm \
  --cores 2 \
  --memory 2048 \
  --swap 512 \
  --net0 name=eth0,bridge=vmbr0,ip=dhcp

# Start container
pct start 999

# Enter container
pct enter 999

# Install Docker inside LXC
apt update && apt upgrade -y
apt install -y curl git
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
usermod -aG docker ubuntu

# Enable nested containerization for LXC
# Edit /etc/pve/lxc/999.conf on Proxmox host
# Add: features: nesting=1,keyctl=1
```

Then deploy Memento as described above.

## 📚 Additional Resources

- [Next.js Deployment](https://nextjs.org/docs/deployment)
- [Docker Compose Reference](https://docs.docker.com/compose/)
- [Prisma Docker Guide](https://www.prisma.io/docs/guides/deployment/docker)
- [Proxmox LXC Documentation](https://pve.proxmox.com/wiki/Linux_Container)

## 💡 Tips

1. **Use Volumes**: Always use Docker volumes for persistent data
2. **Health Checks**: Enable health checks for auto-restart
3. **Log Rotation**: Prevent disk filling with logs
4. **Monitoring**: Use Portainer or similar for easy management
5. **Testing**: Test in staging environment before production

---

**Need Help?** Check the main README or open an issue on GitHub.
