# 🚀 PM2 Production Deployment Guide - LuckyChit

Complete guide to deploy and manage your LuckyChit application using PM2 in production.

---

## 📋 Table of Contents

1. [Prerequisites](#prerequisites)
2. [Initial Setup](#initial-setup)
3. [Backend Deployment](#backend-deployment)
4. [Flutter App Deployment](#flutter-app-deployment)
5. [PM2 Commands](#pm2-commands)
6. [Monitoring & Logs](#monitoring--logs)
7. [Auto-Start on Server Reboot](#auto-start-on-server-reboot)
8. [Production Best Practices](#production-best-practices)
9. [Troubleshooting](#troubleshooting)

---

## Prerequisites

### System Requirements
- Node.js 16+ installed
- PostgreSQL database running
- PM2 installed globally
- nginx (optional, for reverse proxy)

### Install PM2 Globally

```bash
npm install -g pm2
```

Verify installation:
```bash
pm2 --version
```

---

## Initial Setup

### 1. Clone Repository (if not already done)

```bash
cd /var/www  # or your preferred directory
git clone <your-repo-url> luckychit
cd luckychit
```

### 2. Setup Backend

```bash
cd backend
npm install --production

# Create .env file with production credentials
cp .env.example .env
nano .env  # Edit with production values
```

**Important `.env` settings for production:**

```env
NODE_ENV=production
PORT=3000
DB_HOST=localhost
DB_PORT=5432
DB_NAME=chitfund_prod
DB_USER=your_db_user
DB_PASSWORD=your_secure_password
JWT_SECRET=your_very_secure_random_string_min_32_chars
```

### 3. Create Logs Directory

```bash
mkdir -p logs
```

### 4. Database Setup

```bash
# Create production database
createdb chitfund_prod

# Run migrations (if you have any)
# npm run migrate
```

---

## Backend Deployment

### Option 1: Using ecosystem.config.js (Recommended)

The `ecosystem.config.js` file is already configured in the backend directory.

**Start in Production Mode:**

```bash
cd backend
pm2 start ecosystem.config.js --env production
```

**Key Features Enabled:**
- ✅ Cluster mode (uses all CPU cores)
- ✅ Auto-restart on crashes
- ✅ Memory limit (1GB max)
- ✅ Log rotation
- ✅ Daily cron restart at 3 AM
- ✅ Error tracking with source maps

### Option 2: Simple Start Command

```bash
cd backend
pm2 start server.js --name "luckychit-backend" -i max --env production
```

### Verify Backend is Running

```bash
pm2 list
pm2 logs luckychit-backend
```

You should see:
```
✅ Database models synchronized
⏰ Starting payment reminder scheduler...
🚀 Server running on port 3000
```

---

## Flutter App Deployment

### Option 1: Deploy as Web App

**Build Flutter for Web:**

```bash
cd luckychit
flutter build web --release
```

**Serve with PM2 using http-server:**

```bash
# Install http-server globally
npm install -g http-server

# Start with PM2
pm2 start http-server --name "luckychit-web" -- -p 8080 -d false -c-1 build/web
```

**Or using a custom Node.js server:**

Create `luckychit/server.js`:

```javascript
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 8080;

app.use(express.static(path.join(__dirname, 'build/web')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build/web', 'index.html'));
});

app.listen(PORT, () => {
  console.log(`Flutter app running on port ${PORT}`);
});
```

Then start with PM2:

```bash
cd luckychit
npm install express
pm2 start server.js --name "luckychit-web"
```

### Option 2: Deploy as Mobile App

For Android/iOS, build and deploy to app stores:

```bash
# Android
cd luckychit
flutter build apk --release
flutter build appbundle --release

# iOS
flutter build ipa --release
```

Upload to Google Play Store / Apple App Store.

---

## PM2 Commands

### Basic Commands

```bash
# List all processes
pm2 list
pm2 ls

# Show detailed info
pm2 show luckychit-backend

# Monitor in real-time
pm2 monit

# Stop application
pm2 stop luckychit-backend

# Restart application
pm2 restart luckychit-backend

# Reload (zero-downtime restart)
pm2 reload luckychit-backend

# Delete from PM2
pm2 delete luckychit-backend

# Stop all
pm2 stop all

# Restart all
pm2 restart all
```

### Advanced Commands

```bash
# Restart with different env
pm2 restart luckychit-backend --env production

# Scale to 4 instances
pm2 scale luckychit-backend 4

# Reset restart counter
pm2 reset luckychit-backend

# Update PM2
pm2 update
```

---

## Monitoring & Logs

### View Logs

```bash
# View all logs (live)
pm2 logs

# View specific app logs
pm2 logs luckychit-backend

# View only errors
pm2 logs luckychit-backend --err

# View last 200 lines
pm2 logs luckychit-backend --lines 200

# Clear logs
pm2 flush
```

### Log Files Location

Logs are stored in:
```
backend/logs/
├── err.log       # Error logs
├── out.log       # Output logs
└── combined.log  # Combined logs
```

### Real-time Monitoring

```bash
# CPU and Memory monitoring
pm2 monit

# Web-based monitoring (PM2 Plus - optional)
pm2 plus
```

### Install PM2 Log Rotate (Recommended)

```bash
pm2 install pm2-logrotate

# Configure log rotation
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30
pm2 set pm2-logrotate:compress true
```

---

## Auto-Start on Server Reboot

### Generate Startup Script

```bash
# Generate startup script
pm2 startup

# This will output a command like:
# sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u youruser --hp /home/youruser

# Copy and run the command it outputs
```

### Save Current Process List

```bash
pm2 save
```

Now PM2 will automatically restart your apps after server reboot!

### Test Auto-Start

```bash
# Reboot server
sudo reboot

# After reboot, check if apps are running
pm2 list
```

---

## Production Best Practices

### 1. Environment Variables

✅ **DO:**
- Use `.env` file for sensitive data
- Set `NODE_ENV=production`
- Use strong JWT secrets (min 32 characters)
- Use different credentials for production

❌ **DON'T:**
- Commit `.env` to Git
- Use development credentials in production
- Use weak or default passwords

### 2. Security

```bash
# Create limited user for PM2
sudo adduser pm2user
sudo -u pm2user pm2 start ecosystem.config.js

# Setup firewall
sudo ufw allow 3000/tcp  # Backend port
sudo ufw allow 80/tcp    # HTTP
sudo ufw allow 443/tcp   # HTTPS
sudo ufw enable
```

### 3. Reverse Proxy with nginx (Recommended)

**Install nginx:**

```bash
sudo apt update
sudo apt install nginx
```

**Configure nginx:**

Create `/etc/nginx/sites-available/luckychit`:

```nginx
server {
    listen 80;
    server_name your-domain.com;

    # Backend API
    location /api {
        proxy_pass http://localhost:3000;
        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_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }

    # Flutter Web App
    location / {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
```

**Enable site:**

```bash
sudo ln -s /etc/nginx/sites-available/luckychit /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### 4. SSL Certificate (Let's Encrypt)

```bash
# Install certbot
sudo apt install certbot python3-certbot-nginx

# Get certificate
sudo certbot --nginx -d your-domain.com

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

### 5. Database Backups

**Automated daily backup script:**

Create `backup.sh`:

```bash
#!/bin/bash
BACKUP_DIR="/var/backups/postgres"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

pg_dump -U your_db_user chitfund_prod > $BACKUP_DIR/backup_$DATE.sql

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

**Schedule with cron:**

```bash
crontab -e

# Add this line (runs daily at 2 AM):
0 2 * * * /path/to/backup.sh
```

### 6. Health Checks

Add health check endpoint in your backend:

```javascript
// In backend/server.js or routes
app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});
```

Monitor with:

```bash
curl http://localhost:3000/health
```

---

## Troubleshooting

### ⚠️ CRITICAL: bcrypt "invalid ELF header" Error

**Symptoms:**
```
Error: /path/to/bcrypt_lib.node: invalid ELF header
code: 'ERR_DLOPEN_FAILED'
```

**Cause:** bcrypt was installed on Windows but running on Linux (native bindings are platform-specific)

**Solution:**
```bash
cd backend

# Remove all modules and rebuild for Linux
rm -rf node_modules package-lock.json
npm install

# Restart PM2
pm2 restart luckychit-backend
```

**Prevention:** Always run `npm install` on the target server, never copy `node_modules/` from another OS.

### App Crashes Immediately

```bash
# Check logs
pm2 logs luckychit-backend --lines 100

# Common issues:
# - Missing .env file
# - Database connection failed
# - Port already in use
# - Missing dependencies
# - Native module platform mismatch (bcrypt, etc.)
```

### Database Connection Issues

```bash
# Check PostgreSQL is running
sudo systemctl status postgresql

# Check connection
psql -U your_db_user -d chitfund_prod

# Check .env credentials
cat backend/.env
```

### Port Already in Use

```bash
# Find process using port 3000
lsof -i :3000
# or
netstat -tulpn | grep 3000

# Kill process
kill -9 <PID>
```

### High Memory Usage

```bash
# Check memory usage
pm2 monit

# Reduce instances if needed
pm2 scale luckychit-backend 2

# Or increase memory limit in ecosystem.config.js
max_memory_restart: '2G'
```

### Zero-Downtime Deployment

```bash
# Pull latest code
git pull origin main

# Install dependencies
cd backend && npm install

# Reload without downtime
pm2 reload luckychit-backend

# Or use deployment command
pm2 deploy production update
```

### Reset Everything

```bash
# Stop all PM2 processes
pm2 kill

# Remove saved process list
pm2 save --force

# Start fresh
cd backend
pm2 start ecosystem.config.js --env production
pm2 save
```

---

## Quick Reference Card

```bash
# Start
pm2 start ecosystem.config.js --env production

# Monitor
pm2 monit

# Logs
pm2 logs

# Restart
pm2 reload luckychit-backend

# Status
pm2 list

# Save
pm2 save

# Startup
pm2 startup
```

---

## 📊 Monitoring Dashboard (Optional)

### PM2 Plus (Free for 1 server)

```bash
# Register at https://pm2.io
pm2 plus
# Follow instructions to link
```

**Features:**
- Real-time monitoring
- Exception tracking
- Custom metrics
- Email alerts
- Transaction tracing

---

## 🎯 Production Checklist

Before going live:

- [ ] `.env` configured with production credentials
- [ ] Database setup and migrated
- [ ] PM2 installed and configured
- [ ] Logs directory created
- [ ] App starts successfully with PM2
- [ ] Auto-start on reboot configured (`pm2 startup` + `pm2 save`)
- [ ] nginx reverse proxy setup (optional but recommended)
- [ ] SSL certificate installed
- [ ] Database backups automated
- [ ] Monitoring setup (PM2 monit or PM2 Plus)
- [ ] Health check endpoint working
- [ ] Firewall configured
- [ ] Log rotation setup
- [ ] Test app functionality
- [ ] Load testing completed

---

## 🆘 Support

**PM2 Documentation:** https://pm2.keymetrics.io/docs/  
**PM2 GitHub:** https://github.com/Unitech/pm2

---

## 📝 Example Production Workflow

```bash
# Initial deployment
cd /var/www/luckychit/backend
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup

# Updates (zero-downtime)
git pull origin main
npm install
pm2 reload luckychit-backend

# Daily monitoring
pm2 monit              # Check performance
pm2 logs --lines 50    # Check recent logs
```

---

**Your LuckyChit app is now production-ready with PM2! 🚀**

_For additional support, refer to the PM2 documentation or your DevOps team._

