> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xem.email/llms.txt
> Use this file to discover all available pages before exploring further.

# Kubernetes Deployment

> Deploy Posthoot on Kubernetes for production environments

# Kubernetes Deployment

This guide covers deploying Posthoot on Kubernetes for production environments. Kubernetes provides excellent scalability, reliability, and management capabilities for your Posthoot instance.

## Prerequisites

Before you begin, ensure you have:

* **Kubernetes cluster** (v1.20 or later)
* **kubectl** configured and connected to your cluster
* **Docker registry** access for pushing images
* **NGINX Ingress Controller** installed
* **cert-manager** installed for SSL certificates
* **Storage class** configured for persistent volumes

## Quick Start

### 1. Clone and Navigate

```bash theme={"dark"}
git clone https://github.com/posthoot/posthoot-backend.go.git
cd posthoot-backend/server/k8s
```

### 2. Configure Secrets

Edit `secret.yaml` and replace the base64-encoded values:

```bash theme={"dark"}
# Generate base64 values for your secrets
echo -n "your-actual-password" | base64
```

Update these values in `secret.yaml`:

* `POSTGRES_PASSWORD`
* `POSTGRES_USER`
* `POSTGRES_DB`
* `JWT_SECRET`
* `AWS_ACCESS_KEY_ID` (if using S3)
* `AWS_SECRET_ACCESS_KEY` (if using S3)
* `SMTP_*` credentials (if using SMTP)

### 3. Update Configuration

Edit `configmap.yaml` for non-sensitive settings:

* Update domain names in `ingress.yaml`
* Adjust resource limits if needed
* Configure environment-specific settings

### 4. Deploy

```bash theme={"dark"}
# Make deployment script executable
chmod +x deploy.sh

# Deploy everything
./deploy.sh --registry your-registry --tag latest
```

## Architecture

The Kubernetes setup includes:

### Core Components

* **Namespace**: `posthoot-server` for resource isolation
* **PostgreSQL**: Database with persistent storage (10Gi)
* **Redis**: Cache with persistent storage (5Gi)
* **Server**: Application replicas with load balancing
* **Asynqmon**: Background job monitoring dashboard

### Networking

* **Services**: Internal communication between components
* **Ingress**: External access with SSL termination
* **Network Policies**: Security rules for pod communication

### Storage

* **Persistent Volumes**: Data persistence for database and cache
* **ConfigMaps**: Non-sensitive configuration
* **Secrets**: Sensitive data management

## Configuration

### Environment Variables

Configuration is split between ConfigMaps and Secrets:

```yaml theme={"dark"}
# configmap.yaml - Non-sensitive data
SERVER_HOST: "0.0.0.0"
SERVER_PORT: "9001"
DB_HOST: "posthoot-postgres"
REDIS_HOST: "posthoot-redis"
ENVIRONMENT: "production"
LOG_LEVEL: "info"

# secret.yaml - Sensitive data
POSTGRES_PASSWORD: "base64-encoded-password"
JWT_SECRET: "base64-encoded-jwt-secret"
AWS_ACCESS_KEY_ID: "base64-encoded-key"
```

### Resource Allocation

Default resource limits:

| Component  | CPU Request | CPU Limit | Memory Request | Memory Limit |
| ---------- | ----------- | --------- | -------------- | ------------ |
| PostgreSQL | 250m        | 500m      | 256Mi          | 512Mi        |
| Redis      | 100m        | 200m      | 128Mi          | 256Mi        |
| Server     | 500m        | 1000m     | 512Mi          | 1Gi          |
| Asynqmon   | 100m        | 200m      | 128Mi          | 256Mi        |

### Scaling Configuration

The setup includes Horizontal Pod Autoscaler:

```yaml theme={"dark"}
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 70
targetMemoryUtilizationPercentage: 80
```

## Management

### Monitoring Deployment

```bash theme={"dark"}
# Check all resources
kubectl get all -n posthoot-server

# View pod status
kubectl get pods -n posthoot-server

# Check services
kubectl get svc -n posthoot-server

# Monitor ingress
kubectl get ingress -n posthoot-server
```

### Logs and Debugging

```bash theme={"dark"}
# View server logs
kubectl logs -n posthoot-server deployment/posthoot-server

# Follow logs in real-time
kubectl logs -f -n posthoot-server deployment/posthoot-server

# Check specific pod logs
kubectl logs -n posthoot-server <pod-name>
```

### Scaling Operations

```bash theme={"dark"}
# Scale server replicas
kubectl scale deployment posthoot-server --replicas=5 -n posthoot-server

# Check HPA status
kubectl get hpa -n posthoot-server

# View HPA details
kubectl describe hpa posthoot-server-hpa -n posthoot-server
```

### Updates and Rollouts

```bash theme={"dark"}
# Update image
kubectl set image deployment/posthoot-server posthoot-server=your-registry/posthoot-server:v1.1.0 -n posthoot-server

# Monitor rollout
kubectl rollout status deployment/posthoot-server -n posthoot-server

# Rollback if needed
kubectl rollout undo deployment/posthoot-server -n posthoot-server
```

## Backup and Recovery

### Database Backup

```bash theme={"dark"}
# Create backup
kubectl exec -n posthoot-server deployment/posthoot-postgres -- pg_dump -U posthoot posthoot > backup.sql

# Restore backup
kubectl exec -n posthoot-server deployment/posthoot-postgres -- psql -U posthoot posthoot < backup.sql
```

### Persistent Volume Backup

For production environments, consider:

* **Velero**: For comprehensive backup and disaster recovery
* **Storage snapshots**: Using your cloud provider's snapshot features
* **Manual backups**: Regular database dumps and file exports

## Security

### Network Policies

The setup includes network policies that:

* Restrict pod-to-pod communication
* Allow only necessary ports
* Control ingress and egress traffic

### Secrets Management

For production, consider:

* **External Secrets Operator**: For cloud-native secrets
* **HashiCorp Vault**: For advanced secrets management
* **Cloud provider secrets**: AWS Secrets Manager, Azure Key Vault

### RBAC

Consider creating specific ServiceAccounts and Roles:

```yaml theme={"dark"}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: posthoot-server
  namespace: posthoot-server
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: posthoot-server-role
  namespace: posthoot-server
rules:
- apiGroups: [""]
  resources: ["configmaps", "secrets"]
  verbs: ["get", "list", "watch"]
```

## Troubleshooting

### Common Issues

#### 1. Image Pull Errors

```bash theme={"dark"}
# Check image availability
kubectl describe pod -n posthoot-server <pod-name>

# Verify image exists in registry
docker pull your-registry/posthoot-server:latest
```

#### 2. Database Connection Issues

```bash theme={"dark"}
# Check PostgreSQL logs
kubectl logs -n posthoot-server deployment/posthoot-postgres

# Test database connectivity
kubectl exec -n posthoot-server deployment/posthoot-postgres -- pg_isready -U posthoot
```

#### 3. Ingress Issues

```bash theme={"dark"}
# Check ingress status
kubectl get ingress -n posthoot-server
kubectl describe ingress posthoot-ingress -n posthoot-server

# Verify NGINX controller
kubectl get pods -n ingress-nginx
```

#### 4. Resource Issues

```bash theme={"dark"}
# Check resource usage
kubectl top pods -n posthoot-server

# View resource limits
kubectl describe pod -n posthoot-server <pod-name>
```

### Debugging Commands

```bash theme={"dark"}
# Port forward for local access
kubectl port-forward -n posthoot-server svc/posthoot-server 9001:80

# Access Asynqmon dashboard
kubectl port-forward -n posthoot-server svc/posthoot-asynqmon 8080:8080

# Execute commands in pods
kubectl exec -it -n posthoot-server deployment/posthoot-server -- /bin/sh
```

## Production Considerations

### Monitoring Setup

Install monitoring stack:

```bash theme={"dark"}
# Install Prometheus Operator
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack

# Install Grafana
helm install grafana grafana/grafana
```

### High Availability

For multi-zone deployments:

* Deploy across multiple availability zones
* Use anti-affinity rules for pod distribution
* Configure proper resource requests and limits
* Set up monitoring and alerting

### Performance Tuning

```yaml theme={"dark"}
# Optimize PostgreSQL
resources:
  requests:
    memory: "512Mi"
    cpu: "500m"
  limits:
    memory: "1Gi"
    cpu: "1000m"

# Optimize Redis
resources:
  requests:
    memory: "256Mi"
    cpu: "200m"
  limits:
    memory: "512Mi"
    cpu: "400m"
```

### Disaster Recovery

1. **Regular backups** of database and persistent volumes
2. **Cross-region replication** for critical data
3. **Documented recovery procedures**
4. **Regular disaster recovery testing**

## Support

For Kubernetes-specific issues:

1. Check the [Kubernetes README](../../server/k8s/README.md)
2. Review [Kubernetes documentation](https://kubernetes.io/docs/)
3. Check cluster events: `kubectl get events -n posthoot-server`
4. Verify resource availability and quotas

## Next Steps

After successful deployment:

1. **Configure monitoring** and alerting
2. **Set up backups** and test recovery
3. **Implement security** best practices
4. **Plan scaling** strategies
5. **Document procedures** for your team
