269 líneas
6.2 KiB
Markdown
269 líneas
6.2 KiB
Markdown
# Deployment con Nginx - API Ping Service
|
|
|
|
Esta guía explica cómo configurar nginx como proxy reverso para el servicio de ping, asegurando que se obtenga correctamente la IP real de los clientes.
|
|
|
|
## 🔧 Configuración de Nginx
|
|
|
|
### 1. Configuración Básica
|
|
|
|
```nginx
|
|
server {
|
|
listen 80;
|
|
server_name your-domain.com;
|
|
|
|
# Configuración para obtener IP real del cliente
|
|
real_ip_header X-Forwarded-For;
|
|
real_ip_recursive on;
|
|
|
|
# IPs confiables (ajustar según tu infraestructura)
|
|
set_real_ip_from 10.0.0.0/8;
|
|
set_real_ip_from 172.16.0.0/12;
|
|
set_real_ip_from 192.168.0.0/16;
|
|
|
|
location / {
|
|
proxy_pass http://127.0.0.1:3000;
|
|
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_set_header X-Forwarded-Host $host;
|
|
proxy_cache_bypass $http_upgrade;
|
|
}
|
|
}
|
|
```
|
|
|
|
### 2. Rate Limiting en Nginx
|
|
|
|
```nginx
|
|
# En el bloque http {}
|
|
http {
|
|
# Zona de rate limiting para API general
|
|
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/h;
|
|
|
|
# Zona específica para ping (más restrictiva)
|
|
limit_req_zone $binary_remote_addr zone=ping:10m rate=5r/10m;
|
|
|
|
# Rate limiting por IP real (después del proxy)
|
|
limit_req_zone $realip_remote_addr zone=real_ip:10m rate=5r/10m;
|
|
}
|
|
|
|
# En el bloque server {}
|
|
server {
|
|
location /api/ping {
|
|
limit_req zone=ping burst=5 nodelay;
|
|
proxy_pass http://127.0.0.1:3000;
|
|
# ... otros headers de proxy
|
|
}
|
|
}
|
|
```
|
|
|
|
### 3. SSL/HTTPS (Recomendado)
|
|
|
|
```nginx
|
|
server {
|
|
listen 443 ssl http2;
|
|
ssl_certificate /path/to/certificate.pem;
|
|
ssl_certificate_key /path/to/private.key;
|
|
|
|
# Headers de seguridad
|
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
|
add_header X-Content-Type-Options "nosniff" always;
|
|
|
|
# ... resto de la configuración
|
|
}
|
|
```
|
|
|
|
## 🌐 Configuración para Cloudflare
|
|
|
|
Si usas Cloudflare, agrega estas IPs confiables:
|
|
|
|
```nginx
|
|
# IPs de Cloudflare (actualizar periódicamente)
|
|
set_real_ip_from 173.245.48.0/20;
|
|
set_real_ip_from 103.21.244.0/22;
|
|
set_real_ip_from 103.22.200.0/22;
|
|
# ... (ver archivo nginx.conf completo)
|
|
|
|
# Headers específicos para Cloudflare
|
|
real_ip_header CF-Connecting-IP;
|
|
```
|
|
|
|
## 🚀 Pasos de Deployment
|
|
|
|
### 1. Preparar la Aplicación
|
|
|
|
```bash
|
|
# Compilar para producción
|
|
npm run build
|
|
|
|
# Iniciar en modo producción
|
|
npm start
|
|
|
|
# O usar PM2 para gestión de procesos
|
|
npm install -g pm2
|
|
pm2 start npm --name "api-ping" -- start
|
|
pm2 save
|
|
pm2 startup
|
|
```
|
|
|
|
### 2. Configurar Nginx
|
|
|
|
```bash
|
|
# Copiar configuración
|
|
sudo cp nginx.conf /etc/nginx/sites-available/api-ping
|
|
sudo ln -s /etc/nginx/sites-available/api-ping /etc/nginx/sites-enabled/
|
|
|
|
# Verificar configuración
|
|
sudo nginx -t
|
|
|
|
# Recargar nginx
|
|
sudo systemctl reload nginx
|
|
```
|
|
|
|
### 3. Variables de Entorno
|
|
|
|
```bash
|
|
# .env.production
|
|
NODE_ENV=production
|
|
TRUST_PROXY=true
|
|
RATE_LIMIT_MAX=10
|
|
RATE_LIMIT_WINDOW_MS=60000
|
|
```
|
|
|
|
## 🔍 Verificación del Setup
|
|
|
|
### 1. Verificar Headers de Proxy
|
|
|
|
```bash
|
|
# Verificar que nginx está pasando los headers correctos
|
|
curl -H "X-Forwarded-For: 203.0.113.1" http://your-domain.com/api/status
|
|
```
|
|
|
|
### 2. Test de Rate Limiting
|
|
|
|
```bash
|
|
# Script para probar rate limiting
|
|
for i in {1..8}; do
|
|
echo "Request $i:"
|
|
curl -s http://your-domain.com/api/ping \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"target":"8.8.8.8","count":1}' \
|
|
| jq '.rateLimit // .error'
|
|
sleep 1
|
|
done
|
|
```
|
|
|
|
### 3. Verificar IP del Cliente
|
|
|
|
El endpoint `/api/status` ahora incluye información de debugging:
|
|
|
|
```json
|
|
{
|
|
"clientInfo": {
|
|
"ip": "203.0.113.1",
|
|
"isProxied": true,
|
|
"userAgent": "curl/7.68.0",
|
|
"proxyHeaders": {
|
|
"x-forwarded-for": "203.0.113.1",
|
|
"x-real-ip": "203.0.113.1"
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
## 🛡️ Seguridad Adicional
|
|
|
|
### 1. Fail2ban para Protección DDoS
|
|
|
|
```ini
|
|
# /etc/fail2ban/jail.local
|
|
[api-ping]
|
|
enabled = true
|
|
port = http,https
|
|
filter = api-ping
|
|
logpath = /var/log/nginx/api-ping-access.log
|
|
maxretry = 20
|
|
bantime = 3600
|
|
findtime = 300
|
|
```
|
|
|
|
### 2. Monitoreo de Logs
|
|
|
|
```bash
|
|
# Monitorear requests sospechosos
|
|
tail -f /var/log/nginx/api-ping-access.log | grep -E "(429|5[0-9]{2})"
|
|
|
|
# Analizar IPs con más requests
|
|
awk '{print $1}' /var/log/nginx/api-ping-access.log | sort | uniq -c | sort -nr | head -10
|
|
```
|
|
|
|
## 📊 Monitoreo y Métricas
|
|
|
|
### 1. Nginx Status
|
|
|
|
```nginx
|
|
location /nginx_status {
|
|
stub_status on;
|
|
access_log off;
|
|
allow 127.0.0.1;
|
|
deny all;
|
|
}
|
|
```
|
|
|
|
### 2. Logs Estructurados
|
|
|
|
```nginx
|
|
log_format api_ping '$remote_addr - $remote_user [$time_local] '
|
|
'"$request" $status $body_bytes_sent '
|
|
'"$http_referer" "$http_user_agent" '
|
|
'"$http_x_forwarded_for" "$http_x_real_ip" '
|
|
'$request_time $upstream_response_time';
|
|
|
|
access_log /var/log/nginx/api-ping-access.log api_ping;
|
|
```
|
|
|
|
## 🔧 Troubleshooting
|
|
|
|
### Problema: IP incorrecta
|
|
|
|
```bash
|
|
# Verificar headers que llegan a la aplicación
|
|
curl -H "X-Debug: true" http://your-domain.com/api/status
|
|
|
|
# Verificar configuración de nginx
|
|
sudo nginx -T | grep -A 10 -B 10 real_ip
|
|
```
|
|
|
|
### Problema: Rate limiting no funciona
|
|
|
|
```bash
|
|
# Verificar que la IP se está obteniendo correctamente
|
|
# La aplicación debe usar la IP real, no la del proxy (127.0.0.1)
|
|
```
|
|
|
|
### Problema: CORS
|
|
|
|
```bash
|
|
# Verificar headers CORS
|
|
curl -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST" \
|
|
-X OPTIONS http://your-domain.com/api/ping -v
|
|
```
|
|
|
|
## 📝 Checklist de Deployment
|
|
|
|
- [ ] Aplicación compilada para producción
|
|
- [ ] PM2 o similar configurado para gestión de procesos
|
|
- [ ] Nginx configurado con proxy_pass
|
|
- [ ] Headers X-Forwarded-* configurados
|
|
- [ ] real_ip_header configurado
|
|
- [ ] IPs confiables (set_real_ip_from) configuradas
|
|
- [ ] Rate limiting configurado en nginx (opcional)
|
|
- [ ] SSL/HTTPS configurado
|
|
- [ ] Headers de seguridad configurados
|
|
- [ ] Logs configurados
|
|
- [ ] Monitoring configurado
|
|
- [ ] Backup y recovery plan preparado
|
|
|
|
Con esta configuración, el servicio obtendrá correctamente la IP real de los clientes incluso cuando esté detrás de nginx, Cloudflare u otros proxies. 🎉
|