Parcourir la Source

docs: comprehensive deployment and development guide

- Add complete deployment guide for production servers
- Add local development setup instructions
- Add PM2 ecosystem configuration for production process management
- Document SSL certificate setup with certbot

Fixes deployment issues and provides complete setup instructions.
uzairrizwan1 il y a 3 mois
Parent
commit
df2db06938
2 fichiers modifiés avec 543 ajouts et 162 suppressions
  1. 524 162
      README.md
  2. 19 0
      ecosystem.config.js

+ 524 - 162
README.md

@@ -120,115 +120,530 @@ UNIQUE (symbol_id, open_time);
120 120
 Joi.number().precision(15)
121 121
 ```
122 122
 
123
-## Installation
124
-
125
-1. **Clone the repository**
126
-   ```bash
127
-   git clone https://git.mqldevelopment.com/muhammad.uzair/market-data-service.git
128
-   cd market-data-service
129
-   ```
130
-
131
-2. **Install dependencies**
132
-   ```bash
133
-   npm install
134
-   ```
135
-
136
-3. **Set up environment variables**
137
-   ```bash
138
-   cp .env.example .env
139
-   ```
140
-   Edit `.env` with your database credentials and other configuration.
141
-
142
-4. **Database setup**
143
-   ```bash
144
-   # Create PostgreSQL database
145
-   createdb market_data
146
-
147
-   # Run migrations
148
-   npx sequelize-cli db:migrate
149
-   ```
150
-
151
-5. **Start the services**
152
-
153
-   ### Windows Setup (with Nginx Proxy) ✅ **RECOMMENDED**
154
-   ```bash
155
-   # Method 1: Manual (as you're currently doing)
156
-   # Terminal 1: Start Node.js server
157
-   node src/server.js
158
-
159
-   # Terminal 2: Start Nginx proxy (run as administrator)
160
-   powershell -ExecutionPolicy Bypass -Command "cd nginx-1.24.0; .\nginx.exe"
161
-   # OR: Right-click nginx.exe → "Run as administrator"
162
-
163
-   # Method 2: Use batch files (alternative)
164
-   # Right-click and "Run as administrator":
165
-   start_proxy.bat
166
-   ```
167
-
168
-   ### Linux/Mac Setup
169
-   ```bash
170
-   # Start development server
171
-   npm run dev
172
-   ```
173
-
174
-The server will start on `http://localhost:3001` and proxy through Nginx on `http://market-price.insightbull.io`
175
-
176
-## Windows Nginx Setup Guide ✅ **YOUR CURRENT METHOD**
177
-
178
-### Quick Start (Your Working Setup)
179
-1. **Start Node.js server**:
180
-   ```bash
181
-   node src/server.js
182
-   ```
183
-
184
-2. **Start Nginx proxy** (run as administrator):
185
-   ```bash
186
-   powershell -ExecutionPolicy Bypass -Command "cd nginx-1.24.0; .\nginx.exe"
187
-   # OR: Right-click nginx.exe → "Run as administrator"
188
-   ```
189
-
190
-3. **Configure MT5 EA**:
191
-   - Set `ApiBaseUrl = "http://market-price.insightbull.io"`
192
-   - Use the nginx proxy URL for better performance
193
-
194
-4. **Stop services**:
195
-   ```bash
196
-   # Stop Nginx
197
-   taskkill /f /im nginx.exe
198
-
199
-   # Stop Node.js
200
-   taskkill /f /im node.exe
201
-   ```
202
-
203
-### Alternative: Batch Files
204
-If you prefer using batch files:
205
-- **`start_proxy.bat`**: Start both services (run as administrator)
206
-- **`stop_proxy.bat`**: Stop both services
207
-
208
-## Windows Batch Files
209
-
210
-The project includes batch files for easy Windows setup:
211
-
212
-### `start_proxy.bat`
213
-- **Purpose**: Starts both Node.js server and Nginx proxy
214
-- **Usage**: Right-click → "Run as administrator"
215
-- **What it does**:
216
-  - Adds `market-price.insightbull.io` to hosts file
217
-  - Starts Node.js server on port 3001
218
-  - Starts Nginx proxy on ports 80/8080
219
-  - Tests connectivity
220
-
221
-### `stop_proxy.bat`
222
-- **Purpose**: Stops both Node.js server and Nginx proxy
223
-- **Usage**: Double-click or run in terminal
224
-- **What it does**:
225
-  - Stops Nginx processes
226
-  - Stops Node.js processes
227
-  - Frees up ports
228
-
229
-### `start_nginx.ps1`
230
-- **Purpose**: PowerShell script to start Nginx only
231
-- **Usage**: `powershell -ExecutionPolicy Bypass -File start_nginx.ps1`
123
+## 🚀 Complete Deployment Guide
124
+
125
+## 📋 Prerequisites (All Versions)
126
+
127
+### Required Software (Latest Stable Versions)
128
+- **Node.js**: v18.x LTS or higher
129
+- **PostgreSQL**: v13.x or higher
130
+- **Nginx**: v1.24.x or higher
131
+- **Git**: Latest version
132
+- **Certbot** (for SSL certificates)
133
+
134
+---
135
+
136
+## 🆕 FRESH SERVER DEPLOYMENT (Step-by-Step)
137
+
138
+### Step 1: Server Preparation
139
+```bash
140
+# Update system packages
141
+sudo apt update && sudo apt upgrade -y
142
+
143
+# Install required tools
144
+sudo apt install -y curl wget git htop nano ufw
145
+```
146
+
147
+### Step 2: Install Node.js (v18.x LTS)
148
+```bash
149
+# Using NodeSource repository
150
+curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
151
+sudo apt-get install -y nodejs
152
+
153
+# Verify installation
154
+node --version  # Should show v18.x.x
155
+npm --version   # Should show latest version
156
+```
157
+
158
+### Step 3: Install PostgreSQL
159
+```bash
160
+# Install PostgreSQL
161
+sudo apt install -y postgresql postgresql-contrib
162
+
163
+# Start and enable PostgreSQL
164
+sudo systemctl enable postgresql
165
+sudo systemctl start postgresql
166
+
167
+# Verify installation
168
+psql --version  # Should show 15.x or higher
169
+```
170
+
171
+### Step 4: Deploy Application
172
+```bash
173
+# Create application directory
174
+sudo mkdir -p /root/market-data-service
175
+sudo chown $USER:$USER /root/market-data-service
176
+cd /root/market-data-service
177
+
178
+# Clone repository (replace with your actual repo URL)
179
+git clone https://git.mqldevelopment.com/muhammad.uzair/market-data-service.git .
180
+# OR copy your project files to this directory
181
+
182
+# Install dependencies
183
+npm install --production
184
+
185
+# Set up environment variables
186
+cat > .env << EOF
187
+DB_TYPE=postgres
188
+DB_HOST=localhost
189
+DB_PORT=5432
190
+DB_NAME=financial_data
191
+DB_USER=postgres
192
+DB_PASSWORD=your_secure_password_here
193
+
194
+PORT=3001
195
+NODE_ENV=production
196
+
197
+JWT_SECRET=your_secure_jwt_secret_key_here
198
+CORS_ORIGIN=*
199
+
200
+LOG_LEVEL=info
201
+EOF
202
+```
203
+
204
+### Step 5: Database Setup
205
+```bash
206
+# Switch to postgres user
207
+sudo -u postgres psql
208
+
209
+# In PostgreSQL shell, run:
210
+CREATE DATABASE financial_data;
211
+ALTER USER postgres PASSWORD 'your_secure_password_here';
212
+GRANT ALL PRIVILEGES ON DATABASE financial_data TO postgres;
213
+\q
214
+
215
+# Exit and run migrations
216
+npx sequelize-cli db:migrate
217
+
218
+# Verify tables were created
219
+sudo -u postgres psql -d financial_data -c "\dt"
220
+```
221
+
222
+### Step 6: Install PM2 (Process Manager)
223
+```bash
224
+# Install PM2 globally
225
+sudo npm install -g pm2
226
+
227
+# Create PM2 ecosystem file
228
+cat > ecosystem.config.js << EOF
229
+module.exports = {
230
+  apps: [{
231
+    name: 'market-data-api',
232
+    script: 'src/server.js',
233
+    instances: 'max',
234
+    exec_mode: 'cluster',
235
+    env: {
236
+      NODE_ENV: 'production',
237
+      PORT: 3001
238
+    },
239
+    error_file: './logs/err.log',
240
+    out_file: './logs/out.log',
241
+    log_file: './logs/combined.log',
242
+    time: true,
243
+    merge_logs: true,
244
+    watch: false,
245
+    max_memory_restart: '1G'
246
+  }]
247
+};
248
+EOF
249
+
250
+# Start with PM2
251
+pm2 start ecosystem.config.js
252
+pm2 save
253
+pm2 startup
254
+
255
+# Verify PM2 status
256
+pm2 status
257
+pm2 logs
258
+```
259
+
260
+### Step 7: Configure Nginx (WITHOUT SSL first)
261
+```bash
262
+# Copy nginx configuration
263
+sudo cp nginx-1.24.0/conf/nginx.conf /etc/nginx/nginx.conf
264
+
265
+# Test configuration
266
+sudo nginx -t
267
+
268
+# Start Nginx
269
+sudo systemctl enable nginx
270
+sudo systemctl start nginx
271
+```
272
+
273
+### Step 8: Install SSL Certificate (Certbot)
274
+```bash
275
+# Install certbot
276
+sudo apt install -y certbot python3-certbot-nginx
277
+
278
+# Generate SSL certificate
279
+sudo certbot --nginx -d your-domain.com
280
+
281
+# Test certificate
282
+sudo certbot certificates
283
+```
284
+
285
+### Step 9: Update Nginx for SSL (After Certificate Generation)
286
+```bash
287
+# Update nginx configuration with SSL
288
+sudo tee /etc/nginx/sites-available/market-data-api << EOF
289
+server {
290
+    listen 80;
291
+    server_name your-domain.com;
292
+
293
+    # Redirect HTTP to HTTPS
294
+    return 301 https://\$server_name\$request_uri;
295
+}
296
+
297
+server {
298
+    listen 443 ssl http2;
299
+    server_name your-domain.com;
300
+
301
+    # SSL Configuration
302
+    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
303
+    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
304
+    ssl_protocols TLSv1.2 TLSv1.3;
305
+    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
306
+    ssl_prefer_server_ciphers off;
307
+
308
+    # Security Headers
309
+    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
310
+    add_header X-Frame-Options DENY always;
311
+    add_header X-Content-Type-Options nosniff always;
312
+    add_header X-XSS-Protection "1; mode=block" always;
313
+
314
+    # API Proxy Settings
315
+    location /api/ {
316
+        proxy_pass http://localhost:3001;
317
+        proxy_http_version 1.1;
318
+        proxy_set_header Upgrade \$http_upgrade;
319
+        proxy_set_header Connection 'upgrade';
320
+        proxy_set_header Host \$host;
321
+        proxy_set_header X-Real-IP \$remote_addr;
322
+        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
323
+        proxy_set_header X-Forwarded-Proto \$scheme;
324
+
325
+        # Timeout and buffer settings
326
+        proxy_connect_timeout 60s;
327
+        proxy_send_timeout 60s;
328
+        proxy_read_timeout 60s;
329
+        proxy_buffering on;
330
+        proxy_buffer_size 4k;
331
+        proxy_buffers 8 4k;
332
+        client_max_body_size 50M;
333
+    }
334
+
335
+    location /health {
336
+        proxy_pass http://localhost:3001/health;
337
+        proxy_http_version 1.1;
338
+        proxy_set_header Host \$host;
339
+        proxy_set_header X-Real-IP \$remote_addr;
340
+        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
341
+        proxy_set_header X-Forwarded-Proto \$scheme;
342
+    }
343
+
344
+    location / {
345
+        return 200 "Market Data API is running. Use /api/ for endpoints\\n";
346
+        add_header Content-Type text/plain;
347
+    }
348
+}
349
+EOF
350
+
351
+# Enable site and restart nginx
352
+sudo ln -s /etc/nginx/sites-available/market-data-api /etc/nginx/sites-enabled/
353
+sudo rm -f /etc/nginx/sites-enabled/default
354
+sudo nginx -t
355
+sudo systemctl restart nginx
356
+```
357
+
358
+### Step 10: Final Testing
359
+```bash
360
+# Test HTTP to HTTPS redirect
361
+curl -I http://your-domain.com
362
+
363
+# Test HTTPS API endpoints
364
+curl https://your-domain.com/health
365
+curl https://your-domain.com/api/health
366
+curl https://your-domain.com/api/symbols
367
+
368
+# Test bulk endpoint
369
+curl -X POST https://your-domain.com/api/live-prices/bulk \
370
+  -H "Content-Type: application/json" \
371
+  -d '{"prices": [{"symbolId": 1, "price": 123.45}]}'
372
+```
373
+
374
+---
375
+
376
+## 💻 LOCAL DEVELOPMENT SETUP
377
+
378
+This section explains how to run the project locally on your development machine.
379
+
380
+### Prerequisites for Local Development
381
+- **Node.js**: v18.x LTS or higher
382
+- **PostgreSQL**: v13.x or higher
383
+- **Git**: Latest version
384
+
385
+### Step-by-Step Local Setup
386
+
387
+#### 1. Clone the Repository
388
+```bash
389
+# Clone from GitHub
390
+git clone https://git.mqldevelopment.com/muhammad.uzair/market-data-service.git
391
+cd market-data-service
392
+
393
+# Install dependencies
394
+npm install
395
+```
396
+
397
+#### 2. Set Up PostgreSQL Database
398
+```bash
399
+# Create local database
400
+createdb financial_data
401
+
402
+# Set up environment variables
403
+cat > .env << EOF
404
+DB_TYPE=postgres
405
+DB_HOST=localhost
406
+DB_PORT=5432
407
+DB_NAME=financial_data
408
+DB_USER=your_local_username
409
+DB_PASSWORD=your_local_password
410
+
411
+PORT=3001
412
+NODE_ENV=development
413
+
414
+JWT_SECRET=your_development_jwt_secret_key
415
+CORS_ORIGIN=http://localhost:3000
416
+
417
+LOG_LEVEL=debug
418
+EOF
419
+```
420
+
421
+#### 3. Run Database Migrations
422
+```bash
423
+# Install Sequelize CLI (if not already installed)
424
+npm install -g sequelize-cli
425
+
426
+# Run migrations to create tables
427
+npx sequelize-cli db:migrate
428
+
429
+# Verify tables were created
430
+psql -d financial_data -c "\dt"
431
+```
432
+
433
+#### 4. Start Development Server
434
+```bash
435
+# Option 1: Using npm script (recommended)
436
+npm run dev
437
+
438
+# Option 2: Using nodemon directly
439
+npx nodemon src/server.js
440
+
441
+# Option 3: Using node directly
442
+node src/server.js
443
+```
444
+
445
+#### 5. Verify Local Setup
446
+```bash
447
+# Test health endpoint
448
+curl http://localhost:3001/health
449
+
450
+# Test API endpoints
451
+curl http://localhost:3001/api/symbols
452
+curl http://localhost:3001/api/live-prices
453
+
454
+# Test bulk endpoint
455
+curl -X POST http://localhost:3001/api/live-prices/bulk \
456
+  -H "Content-Type: application/json" \
457
+  -d '{"prices": [{"symbolId": 1, "price": 123.45}]}'
458
+```
459
+
460
+
461
+## 🔄 UPDATING EXISTING DEPLOYMENT
462
+
463
+### Quick Update (When Code Changes on GitHub)
464
+
465
+```bash
466
+# Navigate to project directory
467
+cd /root/market-data-service
468
+
469
+# Stop the application
470
+pm2 stop market-data-api
471
+
472
+# Backup current deployment (optional but recommended)
473
+cp .env .env.backup
474
+cp ecosystem.config.js ecosystem.config.js.backup
475
+
476
+# Pull latest changes
477
+git pull origin main
478
+
479
+# Install any new dependencies
480
+npm install --production
481
+
482
+# Run database migrations (if schema changed)
483
+npx sequelize-cli db:migrate
484
+
485
+# Restart application
486
+pm2 start ecosystem.config.js
487
+pm2 save
488
+
489
+# Verify everything is working
490
+pm2 status
491
+curl https://your-domain.com/health
492
+```
493
+
494
+### Full Update (Major Changes)
495
+
496
+```bash
497
+# Navigate to project directory
498
+cd /root/market-data-service
499
+
500
+# Create backup
501
+sudo cp -r /root/market-data-service /root/market-data-service-backup-$(date +%Y%m%d_%H%M%S)
502
+
503
+# Stop services
504
+pm2 stop market-data-api
505
+sudo systemctl stop nginx
506
+
507
+# Update code
508
+git fetch origin
509
+git reset --hard origin/main
510
+
511
+# Install dependencies
512
+npm install --production
513
+
514
+# Update environment if needed
515
+nano .env
516
+
517
+# Run migrations
518
+npx sequelize-cli db:migrate
519
+
520
+# Update PM2 configuration if needed
521
+pm2 start ecosystem.config.js
522
+pm2 save
523
+
524
+# Restart nginx
525
+sudo systemctl start nginx
526
+
527
+# Verify deployment
528
+pm2 status
529
+sudo systemctl status nginx
530
+curl https://your-domain.com/health
531
+```
532
+
533
+---
534
+
535
+## 🛠️ Troubleshooting Guide
536
+
537
+### Common Issues & Solutions
538
+
539
+#### 1. PostgreSQL User Already Exists
540
+**Error:** `ERROR: role "postgres" already exists`
541
+
542
+**Solution:**
543
+```bash
544
+# Just set password for existing user
545
+sudo -u postgres psql
546
+ALTER USER postgres PASSWORD 'your_password';
547
+GRANT ALL PRIVILEGES ON DATABASE financial_data TO postgres;
548
+\q
549
+```
550
+
551
+#### 2. SSL Certificate Not Found
552
+**Error:** `cannot load certificate "/etc/letsencrypt/live/.../fullchain.pem"`
553
+
554
+**Solution:**
555
+```bash
556
+# Generate certificate first
557
+sudo certbot --nginx -d your-domain.com
558
+
559
+# Check if certificates exist
560
+ls -la /etc/letsencrypt/live/your-domain.com/
561
+
562
+# Test nginx configuration
563
+sudo nginx -t
564
+```
565
+
566
+#### 3. PM2 Multiple Instances
567
+**Question:** Why are there 8 instances running?
568
+
569
+**Answer:** This is **GOOD for production**:
570
+- Uses all CPU cores efficiently
571
+- Better load distribution
572
+- Fault tolerance
573
+- Zero-downtime restarts
574
+
575
+**To adjust instances:**
576
+```bash
577
+pm2 scale market-data-api 4  # Use 4 instances
578
+pm2 scale market-data-api 1  # Use 1 instance for testing
579
+```
580
+
581
+## 📊 Monitoring & Maintenance
582
+
583
+```bash
584
+# Check service status
585
+pm2 status
586
+sudo systemctl status nginx
587
+sudo systemctl status postgresql
588
+
589
+# View logs
590
+pm2 logs --lines 50
591
+sudo tail -f /var/log/nginx/access.log
592
+sudo tail -f /var/log/nginx/error.log
593
+
594
+```
595
+
596
+### SSL Certificate Auto-Renewal
597
+```bash
598
+# Check renewal status
599
+sudo certbot certificates
600
+sudo systemctl status certbot.timer
601
+
602
+# Manual renewal test
603
+sudo certbot renew --dry-run
604
+```
605
+
606
+---
607
+
608
+## 🔧 Management Commands
609
+
610
+### PM2 Management
611
+```bash
612
+pm2 status              # Check status
613
+pm2 logs                # View logs
614
+pm2 monit               # Real-time monitoring
615
+pm2 restart all         # Restart all apps
616
+pm2 stop all            # Stop all apps
617
+pm2 delete all          # Delete all apps
618
+```
619
+
620
+### Nginx Management
621
+```bash
622
+sudo systemctl status nginx      # Check status
623
+sudo systemctl restart nginx     # Restart nginx
624
+sudo nginx -t                    # Test configuration
625
+sudo tail -f /var/log/nginx/error.log  # View error logs
626
+```
627
+
628
+### Database Management
629
+```bash
630
+# Connect to database
631
+sudo -u postgres psql -d financial_data
632
+
633
+# View tables
634
+\dt
635
+
636
+# View table structure
637
+\d table_name
638
+
639
+# Backup database
640
+pg_dump financial_data > backup.sql
641
+
642
+# Restore database
643
+psql financial_data < backup.sql
644
+```
645
+
646
+---
232 647
 
233 648
 ## Environment Variables
234 649
 
@@ -286,24 +701,6 @@ CORS_ORIGIN=*
286 701
 - `POST /api/live-prices/bulk` - Bulk update live prices
287 702
 - `DELETE /api/live-prices/:symbolId` - Delete live price
288 703
 
289
-## Database Management
290
-
291
-The database schema is managed through Sequelize migrations and models:
292
-
293
-- Models are defined in `src/models/`
294
-- Migrations are stored in `migrations/`
295
-- Associations are configured in `src/models/index.js`
296
-
297
-Key entities:
298
-- **Symbol**: Financial instrument metadata
299
-- **Candle1h**: Hourly OHLCV data
300
-- **LivePrice**: Real-time market prices
301
-
302
-To update the database schema:
303
-1. Create a new migration: `npx sequelize-cli migration:generate --name description`
304
-2. Implement schema changes in the migration file
305
-3. Run migrations: `npx sequelize-cli db:migrate`
306
-
307 704
 ## Development
308 705
 
309 706
 ### Available Scripts
@@ -317,24 +714,6 @@ To update the database schema:
317 714
 - `npm run lint` - Run ESLint
318 715
 - `npm run lint:fix` - Fix ESLint issues
319 716
 
320
-### Code Style
321
-
322
-This project uses ESLint for code linting. Run `npm run lint` to check for issues and `npm run lint:fix` to automatically fix them.
323
-
324
-### Testing
325
-
326
-The project uses Jest with Supertest for endpoint testing. Key features:
327
-
328
-- Integration tests with database cleanup
329
-- Test environment database configuration
330
-- Automatic test isolation with `{ force: true }` sync
331
-- Comprehensive controller tests including livePriceController
332
-
333
-Run tests:
334
-```bash
335
-npm test         # Run full test suite
336
-npm run test:watch  # Run in watch mode
337
-```
338 717
 
339 718
 ### Database Migrations
340 719
 
@@ -356,20 +735,3 @@ npx sequelize-cli db:migrate:undo
356 735
 1. Set `NODE_ENV=production` in your environment
357 736
 2. Run `npm start` to start the production server
358 737
 3. Consider using a process manager like PM2 for production deployments
359
-
360
-## Contributing
361
-
362
-1. Fork the repository
363
-2. Create a feature branch
364
-3. Make your changes
365
-4. Add tests for new features
366
-5. Ensure all tests pass
367
-6. Submit a pull request
368
-
369
-## License
370
-
371
-ISC License - see LICENSE file for details.
372
-
373
-## Support
374
-
375
-For support or questions, please contact the development team.

+ 19 - 0
ecosystem.config.js

@@ -0,0 +1,19 @@
1
+module.exports = {
2
+  apps: [{
3
+    name: 'market-data-api',
4
+    script: 'src/server.js',
5
+    instances: 'max',
6
+    exec_mode: 'cluster',
7
+    env: {
8
+      NODE_ENV: 'production',
9
+      PORT: 3001
10
+    },
11
+    error_file: './logs/err.log',
12
+    out_file: './logs/out.log',
13
+    log_file: './logs/combined.log',
14
+    time: true,
15
+    merge_logs: true,
16
+    watch: false,
17
+    max_memory_restart: '1G'
18
+  }]
19
+};