> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Braian551/viax/llms.txt
> Use this file to discover all available pages before exploring further.

# Production Deployment

> Complete guide to deploying Viax to production on a VPS server

# Production Deployment

Deploy the Viax platform to a production VPS server with proper security, performance optimization, and monitoring.

<Warning>
  Production deployment requires careful attention to security. Never deploy without proper authentication, HTTPS, and security hardening.
</Warning>

## Deployment Overview

### Current Production Setup

<CardGroup cols={2}>
  <Card title="Server" icon="server">
    **VPS Details:**

    * IP: 76.13.114.194
    * OS: Linux (Ubuntu/Debian)
    * Access: SSH root access
  </Card>

  <Card title="Services" icon="layer-group">
    **Stack:**

    * Apache Web Server
    * PHP 8.3+
    * MySQL 8.0+
    * Git for deployments
  </Card>

  <Card title="Backend" icon="code">
    **Location:**

    * Path: `/var/www/viax/backend`
    * URL: `http://76.13.114.194`
    * Repository: GitHub
  </Card>

  <Card title="Database" icon="database">
    **MySQL:**

    * Host: localhost
    * Database: viax\_production
    * User: viax\_user
  </Card>
</CardGroup>

***

## Pre-Deployment Checklist

<Steps>
  <Step title="Code Review">
    * [ ] All features tested locally
    * [ ] No hardcoded credentials
    * [ ] Error handling implemented
    * [ ] Logging configured
    * [ ] Code committed to Git
  </Step>

  <Step title="Environment Configuration">
    * [ ] Production database credentials ready
    * [ ] API keys secured
    * [ ] SMTP settings configured
    * [ ] Environment variables set
  </Step>

  <Step title="Security">
    * [ ] SQL injection prevention (prepared statements)
    * [ ] XSS protection
    * [ ] CORS configured
    * [ ] Input validation
    * [ ] Password hashing (bcrypt)
  </Step>

  <Step title="Performance">
    * [ ] Database indexes created
    * [ ] Query optimization done
    * [ ] Caching strategy planned
    * [ ] Assets optimized
  </Step>

  <Step title="Backup">
    * [ ] Database backup created
    * [ ] Code repository backed up
    * [ ] Rollback plan documented
  </Step>
</Steps>

***

## Backend Deployment

### Step 1: Server Access

```bash theme={null}
# Connect to VPS via SSH
ssh root@76.13.114.194

# Optional: Use SSH key for secure access
ssh -i ~/.ssh/viax_key root@76.13.114.194
```

### Step 2: Initial Server Setup

<Tabs>
  <Tab title="Update System">
    ```bash theme={null}
    # Update package list
    sudo apt update

    # Upgrade installed packages
    sudo apt upgrade -y

    # Install essential tools
    sudo apt install -y git curl wget vim
    ```
  </Tab>

  <Tab title="Install Apache">
    ```bash theme={null}
    # Install Apache
    sudo apt install apache2 -y

    # Start and enable
    sudo systemctl start apache2
    sudo systemctl enable apache2

    # Verify
    sudo systemctl status apache2
    curl http://localhost
    ```
  </Tab>

  <Tab title="Install PHP">
    ```bash theme={null}
    # Add PHP repository
    sudo apt install software-properties-common -y
    sudo add-apt-repository ppa:ondrej/php -y
    sudo apt update

    # Install PHP 8.3 and extensions
    sudo apt install -y \
      php8.3 \
      php8.3-cli \
      php8.3-mysql \
      php8.3-mbstring \
      php8.3-xml \
      php8.3-curl \
      php8.3-gd \
      php8.3-zip \
      libapache2-mod-php8.3

    # Verify
    php -v
    ```
  </Tab>

  <Tab title="Install MySQL">
    ```bash theme={null}
    # Install MySQL
    sudo apt install mysql-server -y

    # Secure installation
    sudo mysql_secure_installation
    # Follow prompts:
    # - Set root password
    # - Remove anonymous users: Yes
    # - Disallow remote root: Yes
    # - Remove test database: Yes
    # - Reload privileges: Yes

    # Start and enable
    sudo systemctl start mysql
    sudo systemctl enable mysql

    # Verify
    sudo systemctl status mysql
    ```
  </Tab>

  <Tab title="Install Composer">
    ```bash theme={null}
    # Download and install Composer
    curl -sS https://getcomposer.org/installer | php
    sudo mv composer.phar /usr/local/bin/composer

    # Verify
    composer --version
    ```
  </Tab>
</Tabs>

### Step 3: Deploy Backend Code

<Steps>
  <Step title="Create Directory Structure">
    ```bash theme={null}
    # Create project directory
    sudo mkdir -p /var/www/viax
    cd /var/www/viax

    # Set ownership
    sudo chown -R $USER:$USER /var/www/viax
    ```
  </Step>

  <Step title="Clone Repository">
    ```bash theme={null}
    # Clone backend repository
    git clone https://github.com/Braian551/viax-backend.git backend
    cd backend

    # Or pull latest changes if already cloned
    git pull origin main
    ```
  </Step>

  <Step title="Install Dependencies">
    ```bash theme={null}
    # Install PHP dependencies
    composer install --no-dev --optimize-autoloader

    # Verify vendor directory created
    ls -la vendor/
    ```
  </Step>

  <Step title="Set Permissions">
    ```bash theme={null}
    # Create necessary directories
    mkdir -p logs uploads

    # Set ownership to web server user
    sudo chown -R www-data:www-data /var/www/viax/backend

    # Set directory permissions
    sudo chmod -R 755 /var/www/viax/backend

    # Writable directories
    sudo chmod -R 775 logs uploads
    sudo chmod -R 775 vendor
    ```
  </Step>
</Steps>

### Step 4: Configure Apache

**Create Virtual Host:**

```bash theme={null}
sudo vim /etc/apache2/sites-available/viax.conf
```

**Content:**

```apache theme={null}
<VirtualHost *:80>
    ServerName 76.13.114.194
    ServerAdmin admin@viax.com
    
    DocumentRoot /var/www/viax/backend
    
    <Directory /var/www/viax/backend>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        
        # Security headers
        Header set X-Content-Type-Options "nosniff"
        Header set X-Frame-Options "SAMEORIGIN"
        Header set X-XSS-Protection "1; mode=block"
    </Directory>
    
    # Error and Access logs
    ErrorLog ${APACHE_LOG_DIR}/viax_error.log
    CustomLog ${APACHE_LOG_DIR}/viax_access.log combined
    
    # PHP settings
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>
</VirtualHost>
```

**Enable Site:**

```bash theme={null}
# Enable site configuration
sudo a2ensite viax.conf

# Enable required modules
sudo a2enmod rewrite
sudo a2enmod headers

# Test configuration
sudo apache2ctl configtest

# Restart Apache
sudo systemctl restart apache2
```

### Step 5: Configure Database

<Steps>
  <Step title="Create Database">
    ```bash theme={null}
    sudo mysql -u root -p
    ```

    ```sql theme={null}
    -- Create database
    CREATE DATABASE viax_production CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

    -- Create user
    CREATE USER 'viax_user'@'localhost' IDENTIFIED BY 'STRONG_PASSWORD_HERE';

    -- Grant privileges
    GRANT ALL PRIVILEGES ON viax_production.* TO 'viax_user'@'localhost';

    -- Apply changes
    FLUSH PRIVILEGES;

    -- Verify
    SHOW DATABASES;
    SELECT User, Host FROM mysql.user WHERE User = 'viax_user';

    EXIT;
    ```
  </Step>

  <Step title="Import Schema">
    ```bash theme={null}
    # Upload your SQL file to server
    scp basededatos.sql root@76.13.114.194:/tmp/

    # Import on server
    mysql -u viax_user -p viax_production < /tmp/basededatos.sql

    # Verify
    mysql -u viax_user -p viax_production -e "SHOW TABLES;"
    ```
  </Step>

  <Step title="Configure Backend Database Connection">
    Edit `/var/www/viax/backend/config/database.php`:

    ```php theme={null}
    <?php
    class Database {
        private $host = 'localhost';
        private $db_name = 'viax_production';
        private $username = 'viax_user';
        private $password = 'STRONG_PASSWORD_HERE';
        private $conn;
        
        public function getConnection() {
            $this->conn = null;
            try {
                $dsn = "mysql:host={$this->host};dbname={$this->db_name};charset=utf8mb4";
                $this->conn = new PDO($dsn, $this->username, $this->password);
                $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            } catch(PDOException $exception) {
                error_log("DB Connection error: " . $exception->getMessage());
                throw new Exception("Database unavailable");
            }
            return $this->conn;
        }
    }
    ?>
    ```
  </Step>
</Steps>

### Step 6: Production PHP Configuration

**Edit `/etc/php/8.3/apache2/php.ini`:**

```ini theme={null}
; Security
expose_php = Off
display_errors = Off
log_errors = On
error_log = /var/log/php/php_errors.log

; Performance
memory_limit = 256M
max_execution_time = 30
upload_max_filesize = 20M
post_max_size = 20M

; Session
session.cookie_httponly = 1
session.cookie_secure = 1  ; Enable when using HTTPS
session.use_strict_mode = 1

; OpCache (performance)
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0  ; Disable in production
```

**Restart Apache:**

```bash theme={null}
sudo systemctl restart apache2
```

### Step 7: Verify Deployment

<Tabs>
  <Tab title="Health Check">
    ```bash theme={null}
    curl http://76.13.114.194/health.php

    # Expected:
    {"status":"ok","timestamp":"..."}
    ```
  </Tab>

  <Tab title="System Verification">
    ```bash theme={null}
    curl http://76.13.114.194/verify_system_json.php

    # Should show database connection and system info
    ```
  </Tab>

  <Tab title="Test Endpoint">
    ```bash theme={null}
    curl -X POST http://76.13.114.194/auth/login.php \
      -H "Content-Type: application/json" \
      -d '{"email":"test@example.com","password":"test123"}'
    ```
  </Tab>
</Tabs>

***

## Mobile App Deployment

### Android Production Build

<Steps>
  <Step title="Configure Build">
    Edit `android/app/build.gradle`:

    ```gradle theme={null}
    android {
        defaultConfig {
            applicationId "com.viax.app"
            minSdkVersion 21
            targetSdkVersion 33
            versionCode 1
            versionName "1.0.0"
        }
        
        signingConfigs {
            release {
                storeFile file("../keystore.jks")
                storePassword System.getenv("KEYSTORE_PASSWORD")
                keyAlias "viax"
                keyPassword System.getenv("KEY_PASSWORD")
            }
        }
        
        buildTypes {
            release {
                signingConfig signingConfigs.release
                minifyEnabled true
                shrinkResources true
            }
        }
    }
    ```
  </Step>

  <Step title="Build APK">
    ```bash theme={null}
    # Clean previous builds
    flutter clean
    flutter pub get

    # Build release APK
    flutter build apk \
      --dart-define=API_BASE_URL=http://76.13.114.194 \
      --release

    # Output: build/app/outputs/flutter-apk/app-release.apk
    ```
  </Step>

  <Step title="Build App Bundle (Google Play)">
    ```bash theme={null}
    # Build AAB for Play Store
    flutter build appbundle \
      --dart-define=API_BASE_URL=http://76.13.114.194 \
      --release

    # Output: build/app/outputs/bundle/release/app-release.aab
    ```
  </Step>
</Steps>

### iOS Production Build

<Steps>
  <Step title="Configure Signing">
    1. Open `ios/Runner.xcworkspace` in Xcode
    2. Select Runner target
    3. Signing & Capabilities tab
    4. Select your team
    5. Ensure provisioning profile is set
  </Step>

  <Step title="Build">
    ```bash theme={null}
    flutter build ios \
      --dart-define=API_BASE_URL=http://76.13.114.194 \
      --release
    ```
  </Step>

  <Step title="Archive for App Store">
    1. In Xcode: Product > Archive
    2. Wait for archive to complete
    3. Window > Organizer
    4. Select archive > Distribute App
    5. Follow App Store distribution flow
  </Step>
</Steps>

***

## Security Hardening

### Firewall Configuration

```bash theme={null}
# Install UFW (Uncomplicated Firewall)
sudo apt install ufw -y

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

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

# Enable firewall
sudo ufw enable

# Check status
sudo ufw status
```

### SSL/TLS Setup (Future)

<Info>
  HTTPS is highly recommended for production. Use Let's Encrypt for free SSL certificates.
</Info>

```bash theme={null}
# Install Certbot
sudo apt install certbot python3-certbot-apache -y

# Obtain certificate (requires domain name)
sudo certbot --apache -d viax.com -d www.viax.com

# Auto-renewal is configured automatically
sudo certbot renew --dry-run
```

### Security Best Practices

<AccordionGroup>
  <Accordion title="Disable Directory Listing">
    In Apache config:

    ```apache theme={null}
    Options -Indexes
    ```
  </Accordion>

  <Accordion title="Hide PHP Version">
    In `php.ini`:

    ```ini theme={null}
    expose_php = Off
    ```
  </Accordion>

  <Accordion title="Restrict File Uploads">
    ```php theme={null}
    // Validate file types
    $allowed = ['jpg', 'jpeg', 'png', 'pdf'];
    $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) {
        throw new Exception('Invalid file type');
    }

    // Check file size
    if ($_FILES['file']['size'] > 5 * 1024 * 1024) { // 5MB
        throw new Exception('File too large');
    }
    ```
  </Accordion>

  <Accordion title="Rate Limiting">
    Implement rate limiting for API endpoints:

    ```php theme={null}
    // Simple rate limit (production: use Redis)
    session_start();
    $key = 'api_calls_' . $_SERVER['REMOTE_ADDR'];

    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = ['count' => 0, 'reset' => time() + 60];
    }

    if (time() > $_SESSION[$key]['reset']) {
        $_SESSION[$key] = ['count' => 0, 'reset' => time() + 60];
    }

    $_SESSION[$key]['count']++;

    if ($_SESSION[$key]['count'] > 100) { // 100 requests per minute
        http_response_code(429);
        die(json_encode(['error' => 'Too many requests']));
    }
    ```
  </Accordion>
</AccordionGroup>

***

## Monitoring & Maintenance

### Server Monitoring

```bash theme={null}
# Check disk space
df -h

# Check memory usage
free -h

# Check running processes
top
# or
htop

# Check Apache status
sudo systemctl status apache2

# Check MySQL status
sudo systemctl status mysql

# View Apache logs
sudo tail -f /var/log/apache2/viax_error.log
sudo tail -f /var/log/apache2/viax_access.log

# View MySQL logs
sudo tail -f /var/log/mysql/error.log
```

### Database Backups

**Automated Backup Script:**

```bash theme={null}
#!/bin/bash
# /var/www/viax/scripts/backup_db.sh

DATE=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="/var/www/viax/backups"
DB_NAME="viax_production"
DB_USER="viax_user"
DB_PASS="YOUR_PASSWORD"

mkdir -p $BACKUP_DIR

# Create backup
mysqldump -u $DB_USER -p$DB_PASS $DB_NAME | gzip > $BACKUP_DIR/viax_$DATE.sql.gz

# Keep only last 7 days
find $BACKUP_DIR -name "viax_*.sql.gz" -mtime +7 -delete

echo "Backup completed: viax_$DATE.sql.gz"
```

**Schedule with Cron:**

```bash theme={null}
# Edit crontab
crontab -e

# Add daily backup at 2 AM
0 2 * * * /var/www/viax/scripts/backup_db.sh >> /var/www/viax/logs/backup.log 2>&1
```

### Update Deployment

**Deployment Script:**

```bash theme={null}
#!/bin/bash
# /var/www/viax/scripts/deploy.sh

cd /var/www/viax/backend

# Pull latest code
git pull origin main

# Install/update dependencies
composer install --no-dev --optimize-autoloader

# Run migrations (if any)
php migrations/run_migrations.php

# Set permissions
sudo chown -R www-data:www-data /var/www/viax/backend
sudo chmod -R 755 /var/www/viax/backend
sudo chmod -R 775 logs uploads

# Restart Apache
sudo systemctl restart apache2

echo "Deployment completed successfully"
```

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="500 Internal Server Error">
    Check Apache error logs:

    ```bash theme={null}
    sudo tail -100 /var/log/apache2/viax_error.log
    ```

    Common causes:

    * PHP syntax errors
    * Missing file permissions
    * Database connection issues
    * Missing PHP extensions
  </Accordion>

  <Accordion title="Database Connection Failed">
    Test connection:

    ```bash theme={null}
    mysql -u viax_user -p viax_production
    ```

    Check:

    * Credentials in database.php
    * MySQL service running
    * User permissions granted
  </Accordion>

  <Accordion title="High Server Load">
    ```bash theme={null}
    # Check processes
    top

    # Enable PHP OpCache
    # In php.ini: opcache.enable=1

    # Optimize MySQL
    sudo mysqltuner
    ```
  </Accordion>
</AccordionGroup>

<Check>
  **Production Deployment Complete!** Your Viax platform is now live and accessible to users.
</Check>
