Configuración de Entorno
Tabla de Contenidos
- Propósito
- ¿Para quién es esto?
- Tipos de Entorno
- Configuración por Servicio
- Variables Compartidas
- Mejores Prácticas de Seguridad
- Referencia de Variables de Entorno
- 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:
| Environment | Purpose | Base de datos | Despliegue Trigger | Configuration File |
|---|---|---|---|---|
| Development | Local dev, feature Pruebas | Local MongoDB | Manual / v*-dev tag | .env (local, not committed) |
| Test | Integration Pruebas, QA | Test MongoDB (cloud) | Git tag v*-test | Azure KeyVault / secure files |
| Production | Live system, real users | Production MongoDB (replica set) | Git tag v*-prod | Azure 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 ConfigurationNODE_ENV=development # Environment: development | test | productionPORT=3001 # Service port
# Database ConfigurationMONGODB_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 & SecurityJWT_SECRET=your-secret-key-minimum-32-characters-long # JWT signing secret (min 32 chars)JWT_EXPIRATION=7d # Token expiration (default: 7d)
# Redis ConfigurationREDIS_HOST=localhost # Redis hostREDIS_PORT=6379 # Redis portREDIS_PASSWORD= # Redis password (optional for dev)
# Kafka ConfigurationKAFKA_BROKERS=localhost:9092 # Kafka broker list (comma-separated)KAFKA_CLIENT_ID=orders-ms # Kafka client identifierKAFKA_GROUP_ID=orders-consumer-group # Consumer group ID
# Email Integration (SendGrid)SENDGRID_API_KEY=SG.xxxxx... # SendGrid API keyEMAIL_FROM=noreply@algesta.com # Default sender email
# Puppeteer ConfigurationPUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser # Chromium path (production)PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=false # Download Chromium (default: false)
# LoggingLOG_LEVEL=debug # Log level: error | warn | info | debugOptional Variables
# CORS ConfigurationCORS_ORIGIN=http://localhost:5173 # Allowed CORS origins (comma-separated)
# Rate LimitingRATE_LIMIT_TTL=60 # Rate limit window in secondsRATE_LIMIT_LIMIT=100 # Max requests per window
# Feature FlagsENABLE_SWAGGER=true # Enable Swagger UI (default: true in dev)ENABLE_COMPODOC=false # Enable Compodoc generationNotifications Microservicio (algesta-ms-notifications-nestjs)
Location: algesta-ms-notifications-nestjs/.env
Port: 3002
Base de datos: notifications_ms
# Application ConfigurationNODE_ENV=developmentPORT=3002
# Database ConfigurationMONGODB_URI=mongodb://localhost:27017/notifications_ms
# Authentication & SecurityJWT_SECRET=your-secret-key-minimum-32-characters-long
# Redis ConfigurationREDIS_HOST=localhostREDIS_PORT=6379
# Kafka ConfigurationKAFKA_BROKERS=localhost:9092KAFKA_CLIENT_ID=notifications-msKAFKA_GROUP_ID=notifications-consumer-group
# Email Integration (SendGrid)SENDGRID_API_KEY=SG.xxxxx... # Required for sending emailsEMAIL_FROM=noreply@algesta.comEMAIL_TEMPLATES_DIR=./src/shared/templates # Email template directory
# Notification ConfigurationNOTIFICATION_RETENTION_DAYS=90 # Auto-delete notifications after N days (default: 90)MAX_RETRY_ATTEMPTS=3 # Max retries for failed notifications
# LoggingLOG_LEVEL=infoProvider Microservicio (algesta-ms-provider-nestjs)
Location: algesta-ms-provider-nestjs/.env
Port: 3003
Base de datos: providers_ms
# Application ConfigurationNODE_ENV=developmentPORT=3003
# Database ConfigurationMONGODB_URI=mongodb://localhost:27017/providers_ms
# Authentication & SecurityJWT_SECRET=your-secret-key-minimum-32-characters-longBCRYPT_SALT_ROUNDS=10 # Password hashing rounds (default: 10)
# Redis ConfigurationREDIS_HOST=localhostREDIS_PORT=6379
# Kafka ConfigurationKAFKA_BROKERS=localhost:9092KAFKA_CLIENT_ID=provider-msKAFKA_GROUP_ID=provider-consumer-group
# Azure Storage (Document Management)AZURE_STORAGE_CONNECTION_STRING=DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.netAZURE_STORAGE_CONTAINER_NAME=documents-dev # Container name (dev/test/prod)AZURE_STORAGE_SAS_EXPIRY_HOURS=24 # SAS token expiration (hours)
# Email IntegrationSENDGRID_API_KEY=SG.xxxxx...EMAIL_FROM=noreply@algesta.com
# Puppeteer (PDF Generation)PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browserPUPPETEER_SKIP_CHROMIUM_DOWNLOAD=false
# Auction ConfigurationAUCTION_DEFAULT_DURATION_HOURS=48 # Default auction durationAUCTION_MIN_BIDS=1 # Minimum bids requiredAUCTION_MAX_INFLATION_PERCENTAGE=20 # Max allowed price inflation (%)
# LoggingLOG_LEVEL=infoAPI Gateway (algesta-api-gateway-nestjs)
Location: algesta-api-gateway-nestjs/.env
Port: 3000
# Application ConfigurationNODE_ENV=developmentPORT=3000
# Microservice URLsMS_ORDERS_URL=http://localhost:3001 # Orders microservice URLMS_NOTIFICATIONS_URL=http://localhost:3002 # Notifications microservice URLMS_PROVIDER_URL=http://localhost:3003 # Provider microservice URL
# Authentication & SecurityJWT_SECRET=your-secret-key-minimum-32-characters-longJWT_EXPIRATION=7d
# Redis Configuration (Caching & Rate Limiting)REDIS_HOST=localhostREDIS_PORT=6379REDIS_PASSWORD=REDIS_DB=0 # Redis database index
# Rate LimitingRATE_LIMIT_MAX=100 # Max requests per windowRATE_LIMIT_WINDOW_MS=60000 # Window in milliseconds (60s)RATE_LIMIT_BLOCK_DURATION=300000 # Block duration after limit exceeded (5m)
# CORS ConfigurationCORS_ORIGIN=http://localhost:5173,http://localhost:3000 # Allowed origins (comma-separated)CORS_CREDENTIALS=true # Allow credentials
# Puppeteer ConfigurationPUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
# LoggingLOG_LEVEL=info
# SwaggerENABLE_SWAGGER=true # Enable Swagger UISWAGGER_PATH=/api # Swagger endpoint pathDashboard (algesta-dashboard-react)
Location: algesta-dashboard-react/.env.local (not committed)
Port: 5173
# API ConfigurationVITE_API_BASE_URL=http://localhost:3000 # API Gateway URL
# Application ConfigurationVITE_APP_TITLE=Algesta Dashboard # App titleVITE_APP_VERSION=0.0.1 # App version
# Feature FlagsVITE_ENABLE_DEVTOOLS=true # Enable React Query DevToolsVITE_ENABLE_MSW=false # Enable Mock Service Worker (for testing)
# AuthenticationVITE_JWT_STORAGE_KEY=algesta_token # LocalStorage key for JWT
# EnvironmentVITE_ENV=development # Environment identifierNote: 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:
| Variable | Services | Purpose | Required | Example |
|---|---|---|---|---|
NODE_ENV | All NestJS | Environment mode | Yes | development |
JWT_SECRET | Orders, Provider, Gateway | JWT signing key | Yes | 32-char-minimum-secret |
REDIS_HOST | All NestJS | Redis host | Yes | localhost |
REDIS_PORT | All NestJS | Redis port | Yes | 6379 |
SENDGRID_API_KEY | Orders, Notifications, Provider | Email service | Yes (prod) | SG.xxx... |
KAFKA_BROKERS | Orders, Notifications, Provider | Event messaging | Yes (prod) | localhost:9092 |
LOG_LEVEL | All NestJS | Logging verbosity | No | info |
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.localVerification: 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
| Environment | Storage Método | Access Control |
|---|---|---|
| Development | Local .env files | Developer discretion |
| Test | Azure Pipeline secure files | Team lead approval |
| Production | Azure KeyVault / GCP Secret Manager | Ops team only |
4. Base de datos Connection Strings
Development:
MONGODB_URI=mongodb://localhost:27017/orders_msProduction (with authentication):
MONGODB_URI=mongodb://user:password@mongodb-prod.example.com:27017/orders_ms?replicaSet=rs0&authSource=adminBest 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.netAZURE_STORAGE_CONTAINER_NAME=documents-prodSecurity:
- 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
| Variable | Service(s) | Required | Default | Description | Example |
|---|---|---|---|---|---|
NODE_ENV | All | Yes | development | Environment mode | production |
PORT | All | Yes | Service-specific | Service port | 3001 |
MONGODB_URI | MS | Yes | N/A | MongoDB connection string | mongodb://localhost:27017/orders_ms |
DB_POOL_MAX | MS | No | 20 | Max DB connections | 20 |
DB_POOL_MIN | MS | No | 5 | Min DB connections | 5 |
JWT_SECRET | MS + Gateway | Yes | N/A | JWT signing key (min 32 chars) | abc123... |
JWT_EXPIRATION | MS + Gateway | No | 7d | Token expiry | 7d, 24h, 3600s |
REDIS_HOST | All NestJS | Yes | localhost | Redis hostname | redis.example.com |
REDIS_PORT | All NestJS | Yes | 6379 | Redis port | 6379 |
REDIS_PASSWORD | All NestJS | No | "" | Redis password | securepass |
KAFKA_BROKERS | MS | Yes (prod) | localhost:9092 | Kafka broker list | kafka1:9092,kafka2:9092 |
SENDGRID_API_KEY | MS | Yes (prod) | N/A | SendGrid API key | SG.xxx |
EMAIL_FROM | MS | Yes (prod) | N/A | Default sender email | noreply@algesta.com |
AZURE_STORAGE_CONNECTION_STRING | Provider MS | No | N/A | Azure Storage connection | DefaultEndpointsProtocol=https;... |
AZURE_STORAGE_CONTAINER_NAME | Provider MS | No | Documentos-dev | Storage container | Documentos-prod |
PUPPETEER_EXECUTABLE_PATH | MS | No | Auto-detect | Chromium path | /usr/bin/chromium |
LOG_LEVEL | All NestJS | No | info | Log verbosity | error, warn, info, debug |
MS_ORDERS_URL | Gateway | Yes | N/A | Orders MS URL | http://localhost:3001 |
MS_NOTIFICATIONS_URL | Gateway | Yes | N/A | Notifications MS URL | http://localhost:3002 |
MS_PROVIDER_URL | Gateway | Yes | N/A | Provider MS URL | http://localhost:3003 |
RATE_LIMIT_MAX | Gateway | No | 100 | Max requests per window | 100 |
RATE_LIMIT_WINDOW_MS | Gateway | No | 60000 | Rate limit window (ms) | 60000 |
CORS_ORIGIN | Gateway | No | * | Allowed CORS origins | http://localhost:5173 |
VITE_API_BASE_URL | Dashboard | Yes | N/A | API Gateway URL | http://localhost:3000 |
VITE_ENABLE_DEVTOOLS | Dashboard | No | false | Enable React Query DevTools | true |
Verification and Pruebas
1. Validate Environment Files
Check for Missing Variables:
# For NestJS servicescd algesta-ms-orders-nestjsnode -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
# Test MongoDB connectionmongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"# Expected: { ok: 1 }3. Test Redis Connection
redis-cli -h $REDIS_HOST -p $REDIS_PORT ping# Expected: PONG4. Test Service Health
# Start servicenpm run start:dev
# Check health endpointcurl http://localhost:3001/health# Expected: {"status":"ok"}5. Test JWT Secret Consistency
# Extract JWT_SECRET from each service's .envgrep JWT_SECRET algesta-ms-orders-nestjs/.envgrep JWT_SECRET algesta-ms-provider-nestjs/.envgrep 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:
- Verify
.envfile exists in service root - Check variable names (case-sensitive)
- Ensure no spaces around
=in.envfile - Restart terminal/IDE to reload environment
Issue: JWT token validation fails across services
Solution:
- Verify
JWT_SECRETis identical in all services:Ventana de terminal diff <(grep JWT_SECRET algesta-ms-orders-nestjs/.env) \<(grep JWT_SECRET algesta-api-gateway-nestjs/.env) - Ensure no trailing whitespace in secret Valors
- Restart all services after updating
Issue: MongoDB connection timeout
Solution:
- Check MongoDB is running:
mongosh --eval "db.version()" - Verify
MONGODB_URIformat:mongodb://host:port/Base de datos - Test connection manually:
mongosh "$MONGODB_URI" - Check firewall/network settings
- Review connection pool settings (increase
DB_POOL_CONNECTION_TIMEOUT)
Issue: Azure Storage authentication fails
Solution:
- Verify connection string format (no line breaks)
- Check storage account key is valid
- Ensure container exists:
az storage container show --name Documentos-dev - Test with Azure Storage Explorer
- For local dev, consider using Azurite emulator
Related Guías:
- Local Development Setup: Step-by-step service setup
- Docker Setup: Environment variables in Docker
- Despliegue Guía: Production environment configuration
- Troubleshooting: Common configuration issues
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