Nexus Nexus - MATLAB Compatible Computing Platform
← Back to Plans

HOME_SERVER_SAAS_SETUP.md

# Home Server SaaS Setup Guide

## Overview

**Why Home Server for MVP?**
- ✅ **Zero infrastructure cost** (use existing hardware)
- ✅ **Fast setup** (no cloud configuration)
- ✅ **Full control** (no vendor lock-in)
- ✅ **Perfect for MVP** (test with real users)
- ✅ **Easy migration** (move to cloud later)

**When to Migrate to Cloud:**
- When you have 50+ paying customers
- When you need 99.9% uptime SLA
- When you need geographic distribution
- When home server can't handle load

---

## Hardware Requirements

### Minimum (For Testing)
- **CPU:** 4 cores (Intel i5 or AMD Ryzen 5)
- **RAM:** 8GB (16GB recommended)
- **Storage:** 100GB free space (SSD recommended)
- **Network:** Stable internet connection (10+ Mbps upload)
- **OS:** Linux (Ubuntu 22.04 LTS recommended)

### Recommended (For Production MVP)
- **CPU:** 8+ cores (Intel i7 or AMD Ryzen 7)
- **RAM:** 16GB+ (32GB for heavy load)
- **Storage:** 500GB+ SSD
- **Network:** 50+ Mbps upload (fiber recommended)
- **OS:** Linux (Ubuntu 22.04 LTS Server)

### Your Current Setup
- Check your current machine specs
- May be sufficient for MVP
- Can always upgrade later

---

## Network Setup

### Step 1: Dynamic DNS (Free Options)

**Why:** Your home IP changes, need stable domain name

**Options:**
1. **DuckDNS** (Free, recommended)
   - Sign up at https://www.duckdns.org
   - Get subdomain: `yourname.duckdns.org`
   - Update script runs every 5 minutes

2. **No-IP** (Free tier available)
   - Sign up at https://www.noip.com
   - Free dynamic DNS
   - Update client available

3. **Cloudflare** (Free, advanced)
   - More complex setup
   - Better for production

**Setup DuckDNS (Recommended):**
```bash
# Install DuckDNS update script
sudo apt-get install curl
mkdir -p ~/duckdns
cd ~/duckdns
nano duck.sh

# Add this content:
#!/bin/bash
echo url="https://www.duckdns.org/update?domains=yourname&token=YOUR_TOKEN&ip=" | curl -k -o ~/duckdns/duck.log -K -

# Make executable
chmod +x duck.sh

# Test
./duck.sh

# Add to crontab (runs every 5 minutes)
crontab -e
# Add: */5 * * * * ~/duckdns/duck.sh >/dev/null 2>&1
```

### Step 2: Port Forwarding

**Why:** Allow external access to your server

**Steps:**
1. Log into your router (usually 192.168.1.1)
2. Find "Port Forwarding" or "Virtual Server"
3. Forward ports:
   - **80** (HTTP) → Your server IP
   - **443** (HTTPS) → Your server IP
   - **Optional:** 8080, 3000 (for development)

**Router Configuration:**
```
Service Name: Octave SaaS
External Port: 80
Internal IP: 192.168.1.XXX (your server)
Internal Port: 80
Protocol: TCP
```

### Step 3: Firewall Configuration

**Ubuntu Firewall (UFW):**
```bash
# Install UFW
sudo apt-get install ufw

# Allow SSH (important!)
sudo ufw allow 22/tcp

# Allow HTTP/HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Enable firewall
sudo ufw enable

# Check status
sudo ufw status
```

### Step 4: Test External Access

**From external network:**
```bash
# Test HTTP
curl http://yourname.duckdns.org

# Test from phone (different network)
# Open browser: http://yourname.duckdns.org
```

---

## Software Stack

### Option A: Simple Stack (Recommended for MVP)

**Components:**
- **Web Server:** Nginx (reverse proxy)
- **Application:** Python Flask/FastAPI or Node.js
- **Database:** PostgreSQL or SQLite (start simple)
- **Process Manager:** systemd or PM2
- **SSL:** Let's Encrypt (free)

**Installation:**
```bash
# Update system
sudo apt-get update && sudo apt-get upgrade -y

# Install Nginx
sudo apt-get install nginx -y

# Install Python (if using Flask/FastAPI)
sudo apt-get install python3 python3-pip python3-venv -y

# Install PostgreSQL (optional, SQLite works for MVP)
sudo apt-get install postgresql postgresql-contrib -y

# Install Node.js (if using Node.js)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
```

### Option B: Docker Stack (Advanced)

**Components:**
- **Containerization:** Docker + Docker Compose
- **Web Server:** Nginx (in container)
- **Application:** Your app (in container)
- **Database:** PostgreSQL (in container)
- **SSL:** Let's Encrypt (in container)

**Benefits:**
- Easy deployment
- Isolated services
- Easy migration to cloud

---

## Application Setup

### Step 1: Create Application Directory

```bash
# Create project directory
mkdir -p ~/octave-saas
cd ~/octave-saas

# Create virtual environment (Python)
python3 -m venv venv
source venv/bin/activate

# Or create Node.js project
npm init -y
```

### Step 2: Basic Flask Application (Example)

**File: `app.py`**
```python
from flask import Flask, request, jsonify
import subprocess
import os
import tempfile

app = Flask(__name__)

@app.route('/')
def index():
    return jsonify({'status': 'Octave SaaS API', 'version': '1.0'})

@app.route('/api/execute', methods=['POST'])
def execute_code():
    """Execute Octave code"""
    data = request.json
    code = data.get('code', '')
    
    # Create temporary file
    with tempfile.NamedTemporaryFile(mode='w', suffix='.m', delete=False) as f:
        f.write(code)
        temp_file = f.name
    
    try:
        # Execute with timeout
        result = subprocess.run(
            ['octave', '--no-gui', '--eval', f"run('{temp_file}')"],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return jsonify({
            'output': result.stdout,
            'error': result.stderr,
            'returncode': result.returncode
        })
    finally:
        # Clean up
        os.unlink(temp_file)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
```

### Step 3: Install Dependencies

```bash
# Python
pip install flask gunicorn

# Or Node.js
npm install express body-parser
```

### Step 4: Run with Gunicorn (Production)

```bash
# Install Gunicorn
pip install gunicorn

# Run application
gunicorn -w 4 -b 0.0.0.0:5000 app:app
```

---

## Nginx Configuration

### Step 1: Create Nginx Config

**File: `/etc/nginx/sites-available/octave-saas`**
```nginx
server {
    listen 80;
    server_name yourname.duckdns.org;

    # Redirect to HTTPS (after SSL setup)
    # return 301 https://$server_name$request_uri;

    # For now, proxy to application
    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        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;
    }

    # Static files (if any)
    location /static {
        alias /home/username/octave-saas/static;
    }
}
```

### Step 2: Enable Site

```bash
# Create symlink
sudo ln -s /etc/nginx/sites-available/octave-saas /etc/nginx/sites-enabled/

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx
```

---

## SSL Certificate (Let's Encrypt)

### Step 1: Install Certbot

```bash
sudo apt-get install certbot python3-certbot-nginx -y
```

### Step 2: Get Certificate

```bash
# Get certificate
sudo certbot --nginx -d yourname.duckdns.org

# Follow prompts
# Enter email
# Agree to terms
# Choose redirect HTTP to HTTPS
```

### Step 3: Auto-Renewal

```bash
# Test renewal
sudo certbot renew --dry-run

# Certbot automatically sets up renewal (runs twice daily)
```

---

## Systemd Service (Auto-Start)

### Step 1: Create Service File

**File: `/etc/systemd/system/octave-saas.service`**
```ini
[Unit]
Description=Octave SaaS Application
After=network.target

[Service]
User=username
Group=username
WorkingDirectory=/home/username/octave-saas
Environment="PATH=/home/username/octave-saas/venv/bin"
ExecStart=/home/username/octave-saas/venv/bin/gunicorn -w 4 -b 127.0.0.1:5000 app:app
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

### Step 2: Enable Service

```bash
# Reload systemd
sudo systemctl daemon-reload

# Enable service
sudo systemctl enable octave-saas

# Start service
sudo systemctl start octave-saas

# Check status
sudo systemctl status octave-saas
```

---

## Security Considerations

### 1. Firewall
- ✅ Only open necessary ports
- ✅ Use UFW or iptables
- ✅ Block unnecessary services

### 2. SSH Security
```bash
# Disable password login (use keys only)
sudo nano /etc/ssh/sshd_config
# Set: PasswordAuthentication no
# Set: PermitRootLogin no

# Restart SSH
sudo systemctl restart sshd
```

### 3. Application Security
- ✅ Use HTTPS (Let's Encrypt)
- ✅ Input validation
- ✅ Rate limiting
- ✅ Authentication/authorization
- ✅ Code execution sandboxing

### 4. Updates
```bash
# Automatic security updates
sudo apt-get install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
```

---

## Monitoring

### Basic Monitoring

**1. Application Logs**
```bash
# View logs
sudo journalctl -u octave-saas -f

# Or if using PM2
pm2 logs
```

**2. System Monitoring**
```bash
# Install monitoring tools
sudo apt-get install htop iotop nethogs -y

# Monitor resources
htop
```

**3. Uptime Monitoring**
- Use external service (UptimeRobot, Pingdom)
- Free tier available
- Alerts if server goes down

---

## Backup Strategy

### 1. Database Backups

```bash
# PostgreSQL backup script
#!/bin/bash
BACKUP_DIR="/home/username/backups"
DATE=$(date +%Y%m%d_%H%M%S)
pg_dump octave_saas > "$BACKUP_DIR/db_$DATE.sql"

# Add to crontab (daily at 2 AM)
# 0 2 * * * /home/username/backup-db.sh
```

### 2. Application Backups

```bash
# Backup application directory
tar -czf backup_$(date +%Y%m%d).tar.gz ~/octave-saas
```

### 3. Off-Site Backup
- Upload to cloud storage (AWS S3, Backblaze)
- Or use rsync to another server

---

## Cost Breakdown

### Home Server Setup (One-Time)
- **Hardware:** $0 (use existing) or $200-$500 (upgrade)
- **Domain:** $0-$15/year (optional, DuckDNS is free)
- **Dynamic DNS:** $0 (DuckDNS free)
- **SSL:** $0 (Let's Encrypt free)
- **Software:** $0 (all open source)

### Monthly Operating Costs
- **Electricity:** $10-$30/month (depending on hardware)
- **Internet:** $0 (already paying)
- **Total:** $10-$30/month

### Comparison to Cloud
- **Cloud (AWS/Azure):** $100-$500/month
- **Home Server:** $10-$30/month
- **Savings:** $90-$470/month

---

## Migration to Cloud (When Ready)

### When to Migrate
- 50+ paying customers
- Need 99.9% uptime
- Need geographic distribution
- Home server can't handle load

### Migration Steps
1. Set up cloud infrastructure
2. Deploy application to cloud
3. Migrate database
4. Update DNS
5. Test thoroughly
6. Switch traffic
7. Keep home server as backup

### Migration Strategy
- Use Docker for easy migration
- Database replication
- Gradual traffic migration
- Rollback plan ready

---

## Quick Start Checklist

### Week 1: Basic Setup
- [ ] Install Ubuntu Server (or use existing)
- [ ] Set up dynamic DNS (DuckDNS)
- [ ] Configure port forwarding
- [ ] Set up firewall
- [ ] Test external access

### Week 2: Application
- [ ] Install web server (Nginx)
- [ ] Create basic application
- [ ] Set up database
- [ ] Configure Nginx reverse proxy
- [ ] Test locally

### Week 3: Security & SSL
- [ ] Set up SSL (Let's Encrypt)
- [ ] Configure firewall
- [ ] Set up authentication
- [ ] Implement rate limiting
- [ ] Security audit

### Week 4: Production
- [ ] Set up systemd service
- [ ] Configure monitoring
- [ ] Set up backups
- [ ] Load testing
- [ ] Launch!

---

## Troubleshooting

### Common Issues

**1. Can't access from outside**
- Check port forwarding
- Check firewall
- Check router settings
- Test with `curl` from external network

**2. SSL certificate issues**
- Check DNS propagation
- Check port 80/443 forwarding
- Check firewall rules
- Verify domain name

**3. Application not starting**
- Check logs: `sudo journalctl -u octave-saas`
- Check permissions
- Check port conflicts
- Check dependencies

**4. Slow performance**
- Check system resources: `htop`
- Check network speed
- Optimize application
- Consider upgrade

---

## Next Steps

1. **This Week:** Set up home server infrastructure
2. **Next Week:** Deploy basic application
3. **Week 3:** Add security and SSL
4. **Week 4:** Launch MVP

**Ready to start? Let's set up your home server!**

---

*Guide Version: 1.0*  
*Last Updated: 2025-01-18*  
*Status: Ready for Implementation*