# LockNKey Kubernetes Deployment Guide

This guide covers deploying the LockNKey application to Digital Ocean Kubernetes Service (DOKS).

## Prerequisites

1. **Digital Ocean Account** with Kubernetes cluster created
2. **Docker Hub** or **Digital Ocean Container Registry** account
3. **kubectl** installed and configured
4. **doctl** (Digital Ocean CLI) installed
5. **kustomize** installed (or kubectl v1.14+)
6. **Domain name** configured with Digital Ocean DNS

## Architecture Overview

```
┌─────────────────────────────────────────────────┐
│                   Internet                      │
└────────────────────┬────────────────────────────┘
                     │
              ┌──────▼──────┐
              │   Ingress   │
              │   (NGINX)   │
              └──────┬──────┘
                     │
        ┌────────────┼────────────┐
        │            │            │
   ┌────▼────┐ ┌────▼────┐ ┌────▼────┐
   │Frontend │ │   Kong   │ │ Supabase│
   │ (Next.js)│ │   API    │ │  Auth   │
   └─────────┘ │ Gateway  │ └─────────┘
               └────┬─────┘
                    │
     ┌──────────────┼──────────────┐
     │              │              │
┌────▼────┐ ┌──────▼─────┐ ┌─────▼─────┐
│  Auth   │ │   Vault    │ │  Quantum  │
│ Service │ │  Service   │ │  Service  │
└─────────┘ └────────────┘ └───────────┘
     │              │              │
     └──────────────┼──────────────┘
                    │
        ┌───────────┼───────────┐
        │           │           │
   ┌────▼────┐ ┌───▼───┐ ┌────▼────┐
   │PostgreSQL│ │ Redis │ │ Storage │
   └─────────┘ └───────┘ └─────────┘
```

## Step 1: Set Up Digital Ocean Kubernetes Cluster

```bash
# Create a Kubernetes cluster
doctl kubernetes cluster create locknkey-cluster \
  --region nyc3 \
  --size s-2vcpu-4gb \
  --count 3 \
  --tag locknkey

# Save kubeconfig
doctl kubernetes cluster kubeconfig save locknkey-cluster

# Verify connection
kubectl cluster-info
```

## Step 2: Set Up Container Registry

### Using Digital Ocean Container Registry

```bash
# Create container registry
doctl registry create locknkey

# Login to registry
doctl registry login

# Get registry endpoint
REGISTRY_ENDPOINT=$(doctl registry get --format Endpoint --no-header)
echo "Registry: $REGISTRY_ENDPOINT"
```

## Step 3: Build and Push Docker Images

```bash
# Build and tag images
docker build -t $REGISTRY_ENDPOINT/frontend:v1.0.0 ./frontend
docker build -t $REGISTRY_ENDPOINT/auth-service:v1.0.0 ./backend/auth-service
docker build -t $REGISTRY_ENDPOINT/vault-service:v1.0.0 ./backend/vault-service
docker build -t $REGISTRY_ENDPOINT/quantum-service:v1.0.0 ./backend/quantum-service

# Push images to registry
docker push $REGISTRY_ENDPOINT/frontend:v1.0.0
docker push $REGISTRY_ENDPOINT/auth-service:v1.0.0
docker push $REGISTRY_ENDPOINT/vault-service:v1.0.0
docker push $REGISTRY_ENDPOINT/quantum-service:v1.0.0
```

## Step 4: Install Required Controllers

### Install NGINX Ingress Controller

```bash
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.1/deploy/static/provider/do/deploy.yaml
```

### Install cert-manager for SSL

```bash
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml
```

### Create ClusterIssuer for Let's Encrypt

```bash
cat <<EOF | kubectl apply -f -
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: your-email@example.com
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx
EOF
```

## Step 5: Configure Secrets

```bash
# Navigate to production overlay
cd kubernetes/overlays/production

# Copy and edit secrets file
cp secrets.env.example secrets.env

# Edit secrets.env with your actual values
nano secrets.env
```

## Step 6: Configure Supabase

1. Create a Supabase project at https://supabase.com
2. Get your project URL and keys from Settings > API
3. Update the following in your secrets.env:
   - NEXT_PUBLIC_SUPABASE_URL
   - NEXT_PUBLIC_SUPABASE_ANON_KEY
   - SUPABASE_SERVICE_ROLE_KEY
   - SUPABASE_JWT_SECRET

## Step 7: Deploy Application

```bash
# Verify configuration (dry run)
kubectl apply -k kubernetes/overlays/production --dry-run=client

# Deploy to cluster
kubectl apply -k kubernetes/overlays/production

# Watch deployment progress
kubectl get pods -n locknkey -w

# Check deployment status
kubectl get all -n locknkey
```

## Step 8: Configure DNS

1. Get the Load Balancer IP:
```bash
kubectl get service -n ingress-nginx ingress-nginx-controller -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
```

2. Configure DNS A records in Digital Ocean:
   - `locknkey.app` → Load Balancer IP
   - `www.locknkey.app` → Load Balancer IP
   - `api.locknkey.app` → Load Balancer IP

## Step 9: Initialize Kong API Gateway

```bash
# Port forward to Kong Admin
kubectl port-forward -n locknkey service/kong-admin 8001:8001

# Configure services and routes
./scripts/setup_kong_routes.sh
```

## Step 10: Verify Deployment

```bash
# Check pod status
kubectl get pods -n locknkey

# Check services
kubectl get services -n locknkey

# Check ingress
kubectl get ingress -n locknkey

# View logs
kubectl logs -n locknkey deployment/frontend
kubectl logs -n locknkey deployment/auth-service
kubectl logs -n locknkey deployment/vault-service
kubectl logs -n locknkey deployment/quantum-service

# Test endpoints
curl https://locknkey.app
curl https://api.locknkey.app/health
```

## Monitoring and Maintenance

### View Application Logs

```bash
# Frontend logs
kubectl logs -f -n locknkey deployment/frontend

# Backend service logs
kubectl logs -f -n locknkey deployment/auth-service
kubectl logs -f -n locknkey deployment/vault-service
kubectl logs -f -n locknkey deployment/quantum-service
```

### Scale Services

```bash
# Scale frontend
kubectl scale deployment/frontend -n locknkey --replicas=5

# Scale quantum service
kubectl scale deployment/quantum-service -n locknkey --replicas=4
```

### Update Application

```bash
# Build new version
docker build -t $REGISTRY_ENDPOINT/frontend:v1.1.0 ./frontend
docker push $REGISTRY_ENDPOINT/frontend:v1.1.0

# Update deployment
kubectl set image deployment/frontend -n locknkey frontend=$REGISTRY_ENDPOINT/frontend:v1.1.0

# Watch rollout
kubectl rollout status deployment/frontend -n locknkey
```

### Backup Database

```bash
# Create database backup
kubectl exec -n locknkey deployment/postgres -- pg_dump -U locknkey_user locknkey > backup.sql
```

## Troubleshooting

### Pod Issues

```bash
# Describe pod for events
kubectl describe pod <pod-name> -n locknkey

# Get pod logs
kubectl logs <pod-name> -n locknkey

# Execute into pod
kubectl exec -it <pod-name> -n locknkey -- /bin/sh
```

### Service Connection Issues

```bash
# Test service connectivity
kubectl run test-pod --image=busybox -it --rm --restart=Never -n locknkey -- wget -qO- http://frontend-service:3000/health

# Check service endpoints
kubectl get endpoints -n locknkey
```

### Storage Issues

```bash
# Check PVC status
kubectl get pvc -n locknkey

# Check PV status
kubectl get pv
```

## Security Considerations

1. **Secrets Management**: Use Digital Ocean Secrets Manager or Sealed Secrets
2. **Network Policies**: Implement Kubernetes Network Policies
3. **Pod Security**: Use Pod Security Standards
4. **RBAC**: Configure proper Role-Based Access Control
5. **Image Scanning**: Enable vulnerability scanning in registry

## Cost Optimization

1. **Node Pool Sizing**: Start with 3 nodes, scale based on load
2. **Resource Limits**: Set appropriate CPU/memory limits
3. **Storage**: Use Digital Ocean Spaces for static assets
4. **Auto-scaling**: Configure Horizontal Pod Autoscaler

```bash
# Enable HPA for frontend
kubectl autoscale deployment/frontend -n locknkey --cpu-percent=50 --min=2 --max=10
```

## Backup and Disaster Recovery

1. **Database Backups**: Configure automated PostgreSQL backups
2. **Persistent Volume Snapshots**: Use DO volume snapshots
3. **Configuration Backup**: Store Kubernetes manifests in Git
4. **Multi-region Setup**: Consider DR cluster in different region

## Support and Resources

- [Digital Ocean Kubernetes Documentation](https://docs.digitalocean.com/products/kubernetes/)
- [Kubernetes Documentation](https://kubernetes.io/docs/)
- [NGINX Ingress Controller](https://kubernetes.github.io/ingress-nginx/)
- [cert-manager Documentation](https://cert-manager.io/docs/)