Deployment strategies for Module Federation are crucial for stability and performance in production environments. Here are detailed deployment solutions:
1. Deployment Architecture Design
Independent Deployment Mode:
shell┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ Host App │ │ Remote App 1│ │ Remote App 2│ │ :3000 │ │ :3001 │ │ :3002 │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ │ │ └───────────────────┼───────────────────┘ │ ┌──────▼──────┐ │ Load Balancer│ └──────┬──────┘ │ ┌──────▼──────┐ │ CDN / Nginx│ └─────────────┘
2. Environment Configuration Management
Development Environment Configuration:
javascript// webpack.config.js const isDevelopment = process.env.NODE_ENV === 'development' module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'app1', filename: 'remoteEntry.js', remotes: { app2: isDevelopment ? 'app2@http://localhost:3002/remoteEntry.js' : 'app2@https://app2.example.com/remoteEntry.js' }, shared: { react: { singleton: true, eager: true }, 'react-dom': { singleton: true, eager: true } } }) ] }
Production Environment Configuration:
javascript// .env.production REMOTE_APP_URL=https://cdn.example.com REMOTE_APP_VERSION=1.2.3 // webpack.config.js const remoteUrl = process.env.REMOTE_APP_URL const remoteVersion = process.env.REMOTE_APP_VERSION module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'app1', remotes: { app2: `app2@${remoteUrl}/app2/${remoteVersion}/remoteEntry.js` } }) ] }
3. CDN Deployment Strategy
Static Asset Upload:
bash# Use AWS S3 + CloudFront aws s3 sync ./dist s3://my-bucket/app1/1.0.0/ --delete aws cloudfront create-invalidation --distribution-id E1234567890 --paths "/*" # Use Alibaba Cloud OSS ossutil cp -rf ./dist oss://my-bucket/app1/1.0.0/ # Use Tencent Cloud COS coscli cp -r ./dist cos://my-bucket/app1/1.0.0/
Nginx Configuration:
nginxserver { listen 80; server_name app1.example.com; # Main application location / { root /var/www/app1; try_files $uri $uri/ /index.html; } # Remote module entry location /remoteEntry.js { root /var/www/app1; add_header Cache-Control "public, max-age=31536000, immutable"; } # Module files location /assets/ { root /var/www/app1; add_header Cache-Control "public, max-age=31536000, immutable"; } # Enable gzip compression gzip on; gzip_types text/javascript application/javascript; }
4. Version Management Strategy
Semantic Versioning:
json{ "version": "1.2.3", "scripts": { "version:patch": "npm version patch && npm run deploy", "version:minor": "npm version minor && npm run deploy", "version:major": "npm version major && npm run deploy" } }
Version Rollback Mechanism:
bash# Deployment script deploy.sh #!/bin/bash VERSION=$1 BACKUP_DIR="/var/backups/app1" CURRENT_DIR="/var/www/app1" # Backup current version if [ -d "$CURRENT_DIR" ]; then cp -r "$CURRENT_DIR" "$BACKUP_DIR/$(date +%Y%m%d_%H%M%S)" fi # Deploy new version cp -r "./dist" "$CURRENT_DIR" # Health check if ! curl -f http://localhost:3000/health; then echo "Health check failed, rolling back..." cp -r "$BACKUP_DIR/latest" "$CURRENT_DIR" exit 1 fi echo "Deployment successful"
5. CI/CD Integration
GitHub Actions Configuration:
yamlname: Deploy Module Federation on: push: branches: [main] jobs: build-and-deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup Node.js uses: actions/setup-node@v2 with: node-version: '16' - name: Install dependencies run: npm ci - name: Build run: npm run build - name: Run tests run: npm test - name: Deploy to S3 uses: jakejarvis/s3-sync-action@master with: args: --delete env: AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_REGION: 'us-east-1' SOURCE_DIR: 'dist' - name: Invalidate CloudFront uses: chetan/invalidate-cloudfront-action@master env: DISTRIBUTION: ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID }} PATHS: '/*' AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_REGION: 'us-east-1'
6. Monitoring and Alerting
Health Check Endpoint:
javascript// health.js app.get('/health', (req, res) => { const health = { status: 'ok', timestamp: new Date().toISOString(), uptime: process.uptime(), memory: process.memoryUsage(), remoteModules: { app2: { loaded: true, version: '1.2.3', lastUpdated: new Date().toISOString() } } } res.json(health) })
Monitoring Metrics:
javascript// metrics.js const Prometheus = require('prom-client') const httpRequestDuration = new Prometheus.Histogram({ name: 'http_request_duration_seconds', help: 'Duration of HTTP requests in seconds', labelNames: ['method', 'route', 'code'] }) const moduleLoadDuration = new Prometheus.Histogram({ name: 'module_load_duration_seconds', help: 'Duration of module loading in seconds', labelNames: ['module', 'status'] }) // Usage example const start = Date.now() await import('remoteApp/Module') moduleLoadDuration.observe( { module: 'remoteApp/Module', status: 'success' }, (Date.now() - start) / 1000 )
7. Disaster Recovery
Backup Strategy:
bash# Regular backup script #!/bin/bash BACKUP_DIR="/backups/$(date +%Y%m%d)" mkdir -p "$BACKUP_DIR" # Backup all applications for app in app1 app2 app3; do cp -r "/var/www/$app" "$BACKUP_DIR/" done # Upload to S3 aws s3 sync "$BACKUP_DIR" s3://my-backups/
Failover Configuration:
nginxupstream app1_cluster { server app1-primary.example.com weight=3; server app1-backup.example.com weight=1; server app1-dr.example.com backup; } server { location / { proxy_pass http://app1_cluster; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; proxy_next_upstream_tries 2; } }
Best Practices Summary:
- Environment Isolation: Complete isolation of development, testing, and production environments
- Version Management: Use semantic versioning, support quick rollback
- CDN Acceleration: Use CDN to distribute static assets, improve loading speed
- Automated Deployment: Integrate CI/CD, achieve automated deployment process
- Monitoring and Alerting: Real-time monitoring of application status, timely detection and resolution of issues
- Backup and Recovery: Regular backups, disaster recovery planning
- Canary Release: Support canary releases, reduce risk
- Complete Documentation: Maintain detailed deployment documentation and operation manuals
Through these deployment strategies, Module Federation applications can ensure stability and reliability in production environments.