# Deployment Guide

Complete guide for deploying Portfolio Host to production.

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Local Development Setup](#local-development-setup)
3. [Docker Build & Run](#docker-build--run)
4. [CI/CD Pipeline](#cicd-pipeline)
5. [Production Deployment](#production-deployment)
6. [Health Checks & Monitoring](#health-checks--monitoring)
7. [Troubleshooting](#troubleshooting)

---

## Prerequisites

- **Node.js**: 20.x or later
- **Docker**: 20.10 or later
- **Docker Compose**: 2.0 or later (optional)
- **Git**: For version control
- **kubectl**: For Kubernetes deployments (if using k3s)

### Environment Setup

1. Clone the repository:
```bash
git clone https://github.com/your-org/hosting-frontend.git
cd hosting-frontend
```

2. Install dependencies:
```bash
npm install
```

3. Create environment files:
```bash
cp .env.local.example .env.local
cp .env.production.example .env.production
```

4. Configure environment variables:
```bash
# .env.production
NEXT_PUBLIC_API_URL=https://api.portfoliohost.com/api
NODE_ENV=production
NEXT_PUBLIC_ENABLE_ANALYTICS=true
```

---

## Local Development Setup

### Development Server

Start the development server:
```bash
npm run dev
```

Server runs at `http://localhost:3000`

### Testing Locally

Run the full test suite:
```bash
# Run all tests
npm test

# Run tests in CI mode (one pass)
npm run test:ci

# Generate coverage report
npm run test:coverage

# Run specific test file
npm test -- --testPathPattern=navbar
```

### Building Locally

Build for production:
```bash
npm run build
```

This generates the `.next/` directory with optimized production artifacts.

### Production Preview

Preview the production build locally:
```bash
npm run build
npm start
```

Server runs at `http://localhost:3000`

---

## Docker Build & Run

### Building the Docker Image

```bash
# Build image
docker build -t hosting-frontend:latest .

# Build with specific tag
docker build -t hosting-frontend:v1.0.0 .

# Build with build arguments
docker build \
  --build-arg NODE_ENV=production \
  -t hosting-frontend:prod \
  .
```

### Running the Container

```bash
# Run in foreground
docker run -p 3000:3000 hosting-frontend:latest

# Run in background
docker run -d \
  --name hosting-frontend \
  -p 3000:3000 \
  hosting-frontend:latest

# Run with environment variables
docker run -p 3000:3000 \
  -e NEXT_PUBLIC_API_URL=https://api.example.com \
  hosting-frontend:latest

# Run with volume mounting (for logs)
docker run -d \
  -p 3000:3000 \
  -v /var/log/app:/app/logs \
  hosting-frontend:latest
```

### Checking Container Health

```bash
# Check container status
docker ps -a | grep hosting-frontend

# View container logs
docker logs hosting-frontend

# View real-time logs
docker logs -f hosting-frontend

# Test health endpoint
curl http://localhost:3000/

# Execute command in container
docker exec hosting-frontend curl http://localhost:3000/health
```

### Docker Compose (Optional)

Create `docker-compose.yml`:
```yaml
version: '3.8'

services:
  hosting-frontend:
    build:
      context: .
      args:
        NODE_ENV: production
    ports:
      - "3000:3000"
    environment:
      NEXT_PUBLIC_API_URL: https://api.portfoliohost.com
      NODE_ENV: production
    healthcheck:
      test: ["CMD", "node", "-e", "require('http').get('http://localhost:3000/', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 5s
    restart: unless-stopped
```

Run with Docker Compose:
```bash
docker-compose up -d
docker-compose logs -f
docker-compose down
```

---

## CI/CD Pipeline

### Gitea CI/CD Workflows

The project includes two CI/CD workflows:

#### 1. Test & Validate Workflow
- **Trigger**: Push to `main` or `develop` branches
- **File**: `.gitea/workflows/test-and-validate.yml`
- **Steps**:
  1. Checkout code
  2. Setup Node.js 20
  3. Install dependencies
  4. Run linter
  5. Run tests with coverage
  6. Validate coverage threshold (90%)
  7. Build Next.js application
  8. Validate bundle size (<250MB)
  9. Build and test Docker image
  10. Run Docker health checks

#### 2. Production Deployment Workflow
- **Trigger**: Push tags starting with `PROD`
- **File**: `.gitea/workflows/deploy-prod.yml`
- **Steps**:
  1. Build Next.js application
  2. Build Docker image
  3. Push to container registry
  4. Configure kubectl
  5. Deploy to Kubernetes (k3s)
  6. Wait for rollout completion

### Running CI/CD Locally

Test the workflow locally using `act`:

```bash
# Install act
brew install act  # macOS
# or download from https://github.com/nektos/act

# Run the test workflow
act push -j test-and-validate

# Run specific workflow
act -l  # List available workflows
```

### Environment Secrets

Configure these secrets in Gitea:

```
PROD_API_URL              = https://api.portfoliohost.com/api
REGISTRY_URL              = registry.example.com
REGISTRY_USER             = your-username
REGISTRY_PASSWORD         = your-password
KUBE_CONFIG               = your-kubeconfig-content
```

---

## Production Deployment

### Prerequisites for Production

1. **Kubernetes Cluster** (k3s recommended)
2. **Container Registry** (Docker Hub, Private Registry, etc.)
3. **DNS Configuration** (for custom domain)
4. **SSL/TLS Certificate** (Let's Encrypt or custom)

### Deployment Process

#### Step 1: Prepare Release

```bash
# Create and push release tag
git tag PROD-v1.0.0
git push origin PROD-v1.0.0
```

This triggers the CI/CD pipeline automatically.

#### Step 2: Monitor Deployment

```bash
# Watch deployment status
kubectl rollout status deployment/hosting-frontend -n hosting

# Check pod status
kubectl get pods -n hosting

# View logs
kubectl logs -f deployment/hosting-frontend -n hosting

# Describe deployment
kubectl describe deployment hosting-frontend -n hosting
```

#### Step 3: Verify Deployment

```bash
# Check service endpoint
kubectl get service hosting-frontend -n hosting

# Test health endpoint
curl https://portfoliohost.com/

# Test API connectivity
curl https://portfoliohost.com/api/health
```

### Kubernetes Manifests

Kubernetes manifests are located in `deploy/k3s/prod/`:

```
deploy/
├── k3s/
│   ├── prod/
│   │   ├── kustomization.yaml
│   │   ├── deployment.yaml
│   │   ├── service.yaml
│   │   └── ingress.yaml
│   └── staging/
│       └── ...
```

### Manual Deployment (without CI/CD)

```bash
# Apply manifests
kubectl apply -k deploy/k3s/prod

# Update image
kubectl set image deployment/hosting-frontend \
  hosting-frontend=hosting-frontend:v1.0.0 \
  -n hosting

# Verify rollout
kubectl rollout status deployment/hosting-frontend -n hosting
```

---

## Health Checks & Monitoring

### Health Check Endpoint

The application includes a built-in health check in the Dockerfile:

```dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD node -e "require('http').get('http://localhost:3000/', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"
```

Test manually:
```bash
curl -f http://localhost:3000/
echo $?  # 0 = healthy, 1 = unhealthy
```

### Kubernetes Liveness & Readiness Probes

Configured in deployment manifests:

```yaml
livenessProbe:
  httpGet:
    path: /
    port: 3000
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 3
  failureThreshold: 3

readinessProbe:
  httpGet:
    path: /
    port: 3000
  initialDelaySeconds: 5
  periodSeconds: 5
  timeoutSeconds: 3
  failureThreshold: 3
```

### Monitoring

#### Logs

```bash
# View application logs
docker logs hosting-frontend

# View Kubernetes logs
kubectl logs -f deployment/hosting-frontend -n hosting

# Search logs
kubectl logs deployment/hosting-frontend -n hosting | grep "error"
```

#### Metrics

Check application performance:

```bash
# CPU and memory usage
kubectl top pods -n hosting

# Pod events
kubectl describe pod <pod-name> -n hosting

# Recent events
kubectl get events -n hosting --sort-by='.lastTimestamp'
```

---

## Troubleshooting

### Build Issues

#### Docker Build Fails

```bash
# Check Docker logs
docker logs <container-id>

# Rebuild with verbose output
docker build --progress=plain -t hosting-frontend:latest .

# Check disk space
docker system df
docker system prune  # Clean up unused images
```

#### Test Coverage Too Low

```bash
# Generate detailed coverage report
npm run test:coverage

# Check specific file coverage
npm test -- --coverage --collectCoverageFrom="components/launch-ui/*.tsx"
```

### Runtime Issues

#### Container Won't Start

```bash
# Check logs
docker logs hosting-frontend

# Check if port is in use
lsof -i :3000

# Run container in interactive mode
docker run -it hosting-frontend:latest /bin/sh
```

#### Kubernetes Pod CrashLoopBackOff

```bash
# Check pod status
kubectl describe pod <pod-name> -n hosting

# View logs
kubectl logs <pod-name> -n hosting

# Check for resource issues
kubectl top nodes
kubectl top pods -n hosting
```

#### API Connection Errors

```bash
# Verify API URL
echo $NEXT_PUBLIC_API_URL

# Test API connectivity
curl https://api.portfoliohost.com/api/health

# Check environment variables in pod
kubectl exec <pod-name> -n hosting -- env | grep API
```

### Performance Issues

#### Slow Application

```bash
# Check container resource limits
kubectl describe deployment hosting-frontend -n hosting

# Increase resources if needed
kubectl set resources deployment hosting-frontend \
  --requests=cpu=500m,memory=512Mi \
  --limits=cpu=1000m,memory=1Gi \
  -n hosting

# Monitor performance
kubectl top pods -n hosting --containers
```

#### High Memory Usage

```bash
# Check for memory leaks
docker stats hosting-frontend

# Restart container
docker restart hosting-frontend

# Or restart Kubernetes pod
kubectl delete pod <pod-name> -n hosting
```

---

## Rollback Procedure

If deployment goes wrong, rollback to previous version:

```bash
# Check rollout history
kubectl rollout history deployment/hosting-frontend -n hosting

# Rollback to previous version
kubectl rollout undo deployment/hosting-frontend -n hosting

# Rollback to specific revision
kubectl rollout undo deployment/hosting-frontend -n hosting --to-revision=2

# Verify rollback
kubectl rollout status deployment/hosting-frontend -n hosting
```

---

## Performance Optimization

### Next.js Optimization

The application includes optimizations:

- ✅ Static site generation (SSG)
- ✅ Incremental Static Regeneration (ISR)
- ✅ Image optimization with Next.js Image component
- ✅ Code splitting and lazy loading
- ✅ Automatic compression

### Docker Optimization

- ✅ Multi-stage build (reduces image size)
- ✅ Alpine Linux base (small footprint)
- ✅ Non-root user (security)
- ✅ Health checks (auto-restart)

### Kubernetes Optimization

- ✅ Resource limits and requests
- ✅ Horizontal Pod Autoscaling (HPA)
- ✅ Pod disruption budgets
- ✅ Regular liveness/readiness probes

---

## Support

For issues or questions:

1. Check logs: `docker logs` or `kubectl logs`
2. Review this guide for troubleshooting steps
3. Contact support: support@portfoliohost.com
4. Report bugs: https://github.com/your-org/hosting-frontend/issues

---

**Last Updated**: 2025-10-17
**Version**: 1.0.0
