# AWS EC2 Free Tier Backend Deployment Guide

## Free Tier Limits (Important)

| Resource | Limit |
|---|---|
| EC2 | `t2.micro` or `t3.micro` — 750 hours/month free (12 months) |
| Storage | 30 GB EBS |
| MongoDB | Do NOT install on EC2 — use **MongoDB Atlas free tier** (512 MB) |

---

## Step 1 — EC2 Instance Setup

Make sure your EC2 instance is configured with:

- **AMI**: Ubuntu 22.04 LTS
- **Instance Type**: `t2.micro` (free tier eligible)
- **Security Group Inbound Rules**:

| Port | Protocol | Source | Purpose |
|------|----------|--------|---------|
| 22 | TCP | Your IP | SSH access |
| 80 | TCP | 0.0.0.0/0 | HTTP |
| 443 | TCP | 0.0.0.0/0 | HTTPS |
| 4000 | TCP | 0.0.0.0/0 | App port (temporary testing) |

---

## Step 2 — Connect to EC2

```bash
ssh -i "your-key.pem" ubuntu@<your-ec2-public-ip>
```

> **Windows tip:** Run this in PowerShell or use PuTTY with your `.ppk` key.

---

## Step 3 — Install Node.js on EC2

```bash
# Update system packages
sudo apt update && sudo apt upgrade -y

# Install Node.js 20 (LTS)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

# Verify installation
node -v
npm -v
```

---

## Step 4 — Install PM2 (Process Manager)

PM2 keeps your app running after you close the SSH session and restarts it on server reboot.

```bash
sudo npm install -g pm2
```

---

## Step 5 — Upload Your Backend Code

### Option A — Git (Recommended)

```bash
# On EC2
sudo apt install -y git
git clone https://github.com/your-username/your-backend-repo.git
cd your-backend-repo/AibitSoft_Admin_Dashboard_Backend
```

### Option B — SCP from Windows Machine

```powershell
# Run in your local PowerShell terminal
scp -i "your-key.pem" -r "D:\Aibitsoft\AibitSoft_Demo_Listing_Project\AibitSoft_Templates_Project\AibitSoft_Admin_Dashboard_Backend" ubuntu@<ec2-ip>:~/backend
```

---

## Step 6 — Configure Environment Variables

```bash
cd ~/backend   # or wherever you uploaded the project
nano .env
```

Paste all your environment variables:

```env
PORT=4000
NODE_ENV=production
MONGODB_URI=mongodb+srv://<user>:<pass>@cluster.mongodb.net/dbname
JWT_SECRET=your_jwt_secret_here

# Cloudinary
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

# SMTP / Nodemailer
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASS=your_app_password

# Zoom
ZOOM_ACCOUNT_ID=your_zoom_account_id
ZOOM_CLIENT_ID=your_zoom_client_id
ZOOM_CLIENT_SECRET=your_zoom_client_secret

# Add any other variables from your local .env
```

> **Save & exit nano:** `Ctrl + X` → `Y` → `Enter`

---

## Step 7 — Install Dependencies & Build

```bash
npm install
npm run build
```

---

## Step 8 — Start with PM2

```bash
# Start the app
pm2 start dist/server.js --name "aibitsoft-backend"

# Save PM2 process list (persists across reboots)
pm2 save

# Generate and run the startup command (copy & run the output command)
pm2 startup

# Useful PM2 commands
pm2 status                        # Check running processes
pm2 logs aibitsoft-backend        # View live logs
pm2 restart aibitsoft-backend     # Restart app
pm2 stop aibitsoft-backend        # Stop app
```

---

## Step 9 — Setup Nginx as Reverse Proxy (Port 80 → 5000)

```bash
# Install Nginx
sudo apt install -y nginx

# Create site config
sudo nano /etc/nginx/sites-available/backend
```

Paste the following Nginx configuration:

```nginx
server {
    listen 80;
    server_name <your-ec2-public-ip>;  # Replace with your IP or domain

    location / {
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_cache_bypass $http_upgrade;
    }
}
```

```bash
# Enable the site
sudo ln -s /etc/nginx/sites-available/backend /etc/nginx/sites-enabled/

# Test Nginx config
sudo nginx -t

# Restart and enable Nginx
sudo systemctl restart nginx
sudo systemctl enable nginx
```

Your API is now accessible at:
```
http://<your-ec2-public-ip>/api/...
```

---

## Step 10 — (Optional) Free HTTPS with Let's Encrypt

> Requires a domain name pointed to your EC2 IP via DNS A record.

```bash
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
```

Certbot will automatically update your Nginx config with SSL. Your API will be available at:
```
https://yourdomain.com/api/...
```

Certificates auto-renew every 90 days.

---

## Step 11 — Update Frontend Environment Variables

In both frontend projects (`AibitSoft_Admin_Dashboard_Frontend` and `User_Dashboard_Frontend`), update the API base URL:

**`.env.local`** (create if not exists):
```env
# Without domain (IP only)
NEXT_PUBLIC_API_URL=http://<your-ec2-public-ip>

# With domain + HTTPS (after Step 10)
NEXT_PUBLIC_API_URL=https://api.yourdomain.com
```

Then redeploy your frontends on Vercel/Netlify.

---

## Full Stack Summary

| Layer | Service | Cost |
|---|---|---|
| Backend (Node.js/Express) | AWS EC2 `t2.micro` | Free (12 months) |
| Database (MongoDB) | MongoDB Atlas M0 | Free forever |
| File Uploads | Cloudinary | Free tier |
| Frontend (Admin) | Vercel / Netlify | Free |
| Frontend (User) | Vercel / Netlify | Free |
| SSL Certificate | Let's Encrypt | Free forever |

---

## Troubleshooting

**App not reachable on port 80?**
```bash
sudo systemctl status nginx       # Check Nginx is running
pm2 status                        # Check app is running
sudo ufw allow 80                 # Allow port in firewall (if ufw is active)
```

**Check app logs for errors:**
```bash
pm2 logs aibitsoft-backend --lines 100
```

**Restart everything after a reboot:**
```bash
pm2 resurrect    # Restore saved PM2 processes
sudo systemctl restart nginx
```

**Test API locally on EC2:**
```bash
curl http://localhost:4000/api/v1/health
```
