Saltearse al contenido

Configuración de Entorno

Tabla de Contenidos

  1. Propósito
  2. ¿Para quién es esto?
  3. Tipos de Entorno
  4. Configuración por Servicio
  5. Variables Compartidas
  6. Mejores Prácticas de Seguridad
  7. Referencia de Variables de Entorno
  8. Verificación y Pruebas

Propósito

Esta guía documenta todas las variables de entorno requeridas en los microservicios de la plataforma Algesta, API gateway y dashboard. Proporciona referencia completa para configurar servicios en entornos de desarrollo, prueba y producción, asegurando configuración apropiada para conexiones de base de datos, integraciones externas, seguridad y configuraciones operacionales.

Siguiendo esta guía, entenderás:

  • Cuáles variables de entorno son requeridas vs. opcionales
  • Valores predeterminados y rangos aceptables
  • Consideraciones de seguridad para datos sensibles
  • Cómo configurar servicios para diferentes entornos
  • Cómo verificar la correctitud de la configuración

¿Para quién es esto?

Esta guía es para desarrolladores configurando entornos locales, ingenieros DevOps desplegando a entornos cloud y administradores de sistemas gestionando infraestructura de producción. Asume familiaridad con variables de entorno, archivos .env y la arquitectura de Algesta.


Environment Types

The Algesta platform operates in three distinct environments, each with different configuration Requisitos:

EnvironmentPurposeBase de datosDespliegue TriggerConfiguration File
DevelopmentLocal dev, feature PruebasLocal MongoDBManual / v*-dev tag.env (local, not committed)
TestIntegration Pruebas, QATest MongoDB (cloud)Git tag v*-testAzure KeyVault / secure files
ProductionLive system, real usersProduction MongoDB (replica set)Git tag v*-prodAzure KeyVault / GCP Secret Manager

Key Differences:

  • Development: Relaxed security, detailed logging, fast iteration
  • Test: Mirrors production, restricted access, automated Pruebas
  • Production: Maximum security, performance optimization, high availability

Configuration by Service

Orders Microservicio (algesta-ms-orders-nestjs)

Location: algesta-ms-orders-nestjs/.env Port: 3001 Base de datos: orders_ms

Required Variables

# Application Configuration
NODE_ENV=development # Environment: development | test | production
PORT=3001 # Service port
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/orders_ms # Full MongoDB connection string
# Database Pool Configuration (Optional, with defaults)
DB_POOL_MAX=20 # Max connections in pool (default: 20)
DB_POOL_MIN=5 # Min connections in pool (default: 5)
DB_POOL_IDLE_TIMEOUT=30000 # Idle timeout in ms (default: 30000)
DB_POOL_CONNECTION_TIMEOUT=2000 # Connection timeout in ms (default: 2000)
DB_SOCKET_TIMEOUT=30000 # Socket timeout in ms (default: 30000)
DB_SERVER_SELECTION_TIMEOUT=5000 # Server selection timeout (default: 5000)
# Authentication & Security
JWT_SECRET=your-secret-key-minimum-32-characters-long # JWT signing secret (min 32 chars)
JWT_EXPIRATION=7d # Token expiration (default: 7d)
# Redis Configuration
REDIS_HOST=localhost # Redis host
REDIS_PORT=6379 # Redis port
REDIS_PASSWORD= # Redis password (optional for dev)
# Kafka Configuration
KAFKA_BROKERS=localhost:9092 # Kafka broker list (comma-separated)
KAFKA_CLIENT_ID=orders-ms # Kafka client identifier
KAFKA_GROUP_ID=orders-consumer-group # Consumer group ID
# Email Integration (SendGrid)
SENDGRID_API_KEY=SG.xxxxx... # SendGrid API key
EMAIL_FROM=noreply@algesta.com # Default sender email
# Puppeteer Configuration
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser # Chromium path (production)
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=false # Download Chromium (default: false)
# Logging
LOG_LEVEL=debug # Log level: error | warn | info | debug

Optional Variables

# CORS Configuration
CORS_ORIGIN=http://localhost:5173 # Allowed CORS origins (comma-separated)
# Rate Limiting
RATE_LIMIT_TTL=60 # Rate limit window in seconds
RATE_LIMIT_LIMIT=100 # Max requests per window
# Feature Flags
ENABLE_SWAGGER=true # Enable Swagger UI (default: true in dev)
ENABLE_COMPODOC=false # Enable Compodoc generation

Notifications Microservicio (algesta-ms-notifications-nestjs)

Location: algesta-ms-notifications-nestjs/.env Port: 3002 Base de datos: notifications_ms

# Application Configuration
NODE_ENV=development
PORT=3002
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/notifications_ms
# Authentication & Security
JWT_SECRET=your-secret-key-minimum-32-characters-long
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
# Kafka Configuration
KAFKA_BROKERS=localhost:9092
KAFKA_CLIENT_ID=notifications-ms
KAFKA_GROUP_ID=notifications-consumer-group
# Email Integration (SendGrid)
SENDGRID_API_KEY=SG.xxxxx... # Required for sending emails
EMAIL_FROM=noreply@algesta.com
EMAIL_TEMPLATES_DIR=./src/shared/templates # Email template directory
# Notification Configuration
NOTIFICATION_RETENTION_DAYS=90 # Auto-delete notifications after N days (default: 90)
MAX_RETRY_ATTEMPTS=3 # Max retries for failed notifications
# Logging
LOG_LEVEL=info

Provider Microservicio (algesta-ms-provider-nestjs)

Location: algesta-ms-provider-nestjs/.env Port: 3003 Base de datos: providers_ms

# Application Configuration
NODE_ENV=development
PORT=3003
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/providers_ms
# Authentication & Security
JWT_SECRET=your-secret-key-minimum-32-characters-long
BCRYPT_SALT_ROUNDS=10 # Password hashing rounds (default: 10)
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
# Kafka Configuration
KAFKA_BROKERS=localhost:9092
KAFKA_CLIENT_ID=provider-ms
KAFKA_GROUP_ID=provider-consumer-group
# Azure Storage (Document Management)
AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net
AZURE_STORAGE_CONTAINER_NAME=documents-dev # Container name (dev/test/prod)
AZURE_STORAGE_SAS_EXPIRY_HOURS=24 # SAS token expiration (hours)
# Email Integration
SENDGRID_API_KEY=SG.xxxxx...
EMAIL_FROM=noreply@algesta.com
# Puppeteer (PDF Generation)
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=false
# Auction Configuration
AUCTION_DEFAULT_DURATION_HOURS=48 # Default auction duration
AUCTION_MIN_BIDS=1 # Minimum bids required
AUCTION_MAX_INFLATION_PERCENTAGE=20 # Max allowed price inflation (%)
# Logging
LOG_LEVEL=info

API Gateway (algesta-api-gateway-nestjs)

Location: algesta-api-gateway-nestjs/.env Port: 3000

# Application Configuration
NODE_ENV=development
PORT=3000
# Microservice URLs
MS_ORDERS_URL=http://localhost:3001 # Orders microservice URL
MS_NOTIFICATIONS_URL=http://localhost:3002 # Notifications microservice URL
MS_PROVIDER_URL=http://localhost:3003 # Provider microservice URL
# Authentication & Security
JWT_SECRET=your-secret-key-minimum-32-characters-long
JWT_EXPIRATION=7d
# Redis Configuration (Caching & Rate Limiting)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0 # Redis database index
# Rate Limiting
RATE_LIMIT_MAX=100 # Max requests per window
RATE_LIMIT_WINDOW_MS=60000 # Window in milliseconds (60s)
RATE_LIMIT_BLOCK_DURATION=300000 # Block duration after limit exceeded (5m)
# CORS Configuration
CORS_ORIGIN=http://localhost:5173,http://localhost:3000 # Allowed origins (comma-separated)
CORS_CREDENTIALS=true # Allow credentials
# Puppeteer Configuration
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
# Logging
LOG_LEVEL=info
# Swagger
ENABLE_SWAGGER=true # Enable Swagger UI
SWAGGER_PATH=/api # Swagger endpoint path

Dashboard (algesta-dashboard-react)

Location: algesta-dashboard-react/.env.local (not committed) Port: 5173

# API Configuration
VITE_API_BASE_URL=http://localhost:3000 # API Gateway URL
# Application Configuration
VITE_APP_TITLE=Algesta Dashboard # App title
VITE_APP_VERSION=0.0.1 # App version
# Feature Flags
VITE_ENABLE_DEVTOOLS=true # Enable React Query DevTools
VITE_ENABLE_MSW=false # Enable Mock Service Worker (for testing)
# Authentication
VITE_JWT_STORAGE_KEY=algesta_token # LocalStorage key for JWT
# Environment
VITE_ENV=development # Environment identifier

Note: Vite requires all environment variables to be prefixed with VITE_ to be exposed to the client.


Shared Variables

These variables are common across multiple services:

VariableServicesPurposeRequiredExample
NODE_ENVAll NestJSEnvironment modeYesdevelopment
JWT_SECRETOrders, Provider, GatewayJWT signing keyYes32-char-minimum-secret
REDIS_HOSTAll NestJSRedis hostYeslocalhost
REDIS_PORTAll NestJSRedis portYes6379
SENDGRID_API_KEYOrders, Notifications, ProviderEmail serviceYes (prod)SG.xxx...
KAFKA_BROKERSOrders, Notifications, ProviderEvent messagingYes (prod)localhost:9092
LOG_LEVELAll NestJSLogging verbosityNoinfo

Synchronization Requisito: JWT_SECRET must be identical across Orders MS, Provider MS, and API Gateway for token validation to work correctly.


Security Best Practices

1. Never Commit Secrets

Git Ignore: Ensure .env files are in .gitignore:

.env
.env.local
.env.*.local
.env.development.local
.env.test.local
.env.production.local

Verification: Run git Estado and confirm .env files are not tracked.

2. Use Strong Secrets

JWT_SECRET Requisitos:

  • Minimum 32 characters
  • Mix of uppercase, lowercase, numbers, symbols
  • Use a secure random generator:
    Ventana de terminal
    node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

SENDGRID_API_KEY:

  • Never use production keys in development
  • Rotate keys quarterly
  • Store in Azure KeyVault or GCP Secret Manager in production

3. Environment-Specific Secrets

EnvironmentStorage MétodoAccess Control
DevelopmentLocal .env filesDeveloper discretion
TestAzure Pipeline secure filesTeam lead approval
ProductionAzure KeyVault / GCP Secret ManagerOps team only

4. Base de datos Connection Strings

Development:

MONGODB_URI=mongodb://localhost:27017/orders_ms

Production (with authentication):

MONGODB_URI=mongodb://user:password@mongodb-prod.example.com:27017/orders_ms?replicaSet=rs0&authSource=admin

Best Practices:

  • Use connection pooling (configured in Base de datos.config.ts)
  • Enable SSL/TLS in production: ?ssl=true
  • Use replica sets for high availability

5. Azure Storage

Local Development (Optional):

  • Use Azure Storage Emulator (Azurite)
  • Or skip Document upload Funcionalidades

Production:

AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=algestaprod;AccountKey=xxx;EndpointSuffix=core.windows.net
AZURE_STORAGE_CONTAINER_NAME=documents-prod

Security:

  • Use Managed Identity in Azure (preferred over connection strings)
  • Generate SAS tokens with minimal permissions and short expiry
  • Rotate storage account keys quarterly

Environment Variable Reference

Completo Variable Table

VariableService(s)RequiredDefaultDescriptionExample
NODE_ENVAllYesdevelopmentEnvironment modeproduction
PORTAllYesService-specificService port3001
MONGODB_URIMSYesN/AMongoDB connection stringmongodb://localhost:27017/orders_ms
DB_POOL_MAXMSNo20Max DB connections20
DB_POOL_MINMSNo5Min DB connections5
JWT_SECRETMS + GatewayYesN/AJWT signing key (min 32 chars)abc123...
JWT_EXPIRATIONMS + GatewayNo7dToken expiry7d, 24h, 3600s
REDIS_HOSTAll NestJSYeslocalhostRedis hostnameredis.example.com
REDIS_PORTAll NestJSYes6379Redis port6379
REDIS_PASSWORDAll NestJSNo""Redis passwordsecurepass
KAFKA_BROKERSMSYes (prod)localhost:9092Kafka broker listkafka1:9092,kafka2:9092
SENDGRID_API_KEYMSYes (prod)N/ASendGrid API keySG.xxx
EMAIL_FROMMSYes (prod)N/ADefault sender emailnoreply@algesta.com
AZURE_STORAGE_CONNECTION_STRINGProvider MSNoN/AAzure Storage connectionDefaultEndpointsProtocol=https;...
AZURE_STORAGE_CONTAINER_NAMEProvider MSNoDocumentos-devStorage containerDocumentos-prod
PUPPETEER_EXECUTABLE_PATHMSNoAuto-detectChromium path/usr/bin/chromium
LOG_LEVELAll NestJSNoinfoLog verbosityerror, warn, info, debug
MS_ORDERS_URLGatewayYesN/AOrders MS URLhttp://localhost:3001
MS_NOTIFICATIONS_URLGatewayYesN/ANotifications MS URLhttp://localhost:3002
MS_PROVIDER_URLGatewayYesN/AProvider MS URLhttp://localhost:3003
RATE_LIMIT_MAXGatewayNo100Max requests per window100
RATE_LIMIT_WINDOW_MSGatewayNo60000Rate limit window (ms)60000
CORS_ORIGINGatewayNo*Allowed CORS originshttp://localhost:5173
VITE_API_BASE_URLDashboardYesN/AAPI Gateway URLhttp://localhost:3000
VITE_ENABLE_DEVTOOLSDashboardNofalseEnable React Query DevToolstrue

Verification and Pruebas

1. Validate Environment Files

Check for Missing Variables:

Ventana de terminal
# For NestJS services
cd algesta-ms-orders-nestjs
node -e "require('dotenv').config(); console.log(process.env)" | grep -E "NODE_ENV|MONGODB_URI|JWT_SECRET"

Expected Output: All required variables should have Valors.

2. Test Base de datos Connection

Ventana de terminal
# Test MongoDB connection
mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"
# Expected: { ok: 1 }

3. Test Redis Connection

Ventana de terminal
redis-cli -h $REDIS_HOST -p $REDIS_PORT ping
# Expected: PONG

4. Test Service Health

Ventana de terminal
# Start service
npm run start:dev
# Check health endpoint
curl http://localhost:3001/health
# Expected: {"status":"ok"}

5. Test JWT Secret Consistency

Ventana de terminal
# Extract JWT_SECRET from each service's .env
grep JWT_SECRET algesta-ms-orders-nestjs/.env
grep JWT_SECRET algesta-ms-provider-nestjs/.env
grep JWT_SECRET algesta-api-gateway-nestjs/.env
# All should match!

6. Test Environment Loading in Code

Add this to any NestJS service’s main.ts during development:

console.log("Environment Check:", {
NODE_ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
MONGODB_URI: process.env.MONGODB_URI ? "Set" : "Missing",
JWT_SECRET: process.env.JWT_SECRET ? "Set" : "Missing",
REDIS_HOST: process.env.REDIS_HOST,
});

Troubleshooting

Issue: Service fails to start with “Missing required environment variables”

Solution:

  1. Verify .env file exists in service root
  2. Check variable names (case-sensitive)
  3. Ensure no spaces around = in .env file
  4. Restart terminal/IDE to reload environment

Issue: JWT token validation fails across services

Solution:

  1. Verify JWT_SECRET is identical in all services:
    Ventana de terminal
    diff <(grep JWT_SECRET algesta-ms-orders-nestjs/.env) \
    <(grep JWT_SECRET algesta-api-gateway-nestjs/.env)
  2. Ensure no trailing whitespace in secret Valors
  3. Restart all services after updating

Issue: MongoDB connection timeout

Solution:

  1. Check MongoDB is running: mongosh --eval "db.version()"
  2. Verify MONGODB_URI format: mongodb://host:port/Base de datos
  3. Test connection manually: mongosh "$MONGODB_URI"
  4. Check firewall/network settings
  5. Review connection pool settings (increase DB_POOL_CONNECTION_TIMEOUT)

Issue: Azure Storage authentication fails

Solution:

  1. Verify connection string format (no line breaks)
  2. Check storage account key is valid
  3. Ensure container exists: az storage container show --name Documentos-dev
  4. Test with Azure Storage Explorer
  5. For local dev, consider using Azurite emulator

Related Guías:

For Support:

  • Review [Base de datos Setup](/04-guides/Base de datos-setup/) for MongoDB configuration
  • Check service READMEs for service-specific variables
  • Contact DevOps team for production secrets access