Deployment Strategies ๐
Deploy your Angular applications to production with confidence. Learn various deployment strategies, hosting platforms, and best practices for different scenarios.
๐ฏ Deployment Options
Section titled โ๐ฏ Deployment OptionsโHosting Types:
- Static Hosting - Netlify, Vercel, GitHub Pages
- Cloud Platforms - AWS, Azure, Google Cloud
- Traditional Servers - Apache, Nginx
- Serverless - AWS Lambda, Azure Functions
- Container Platforms - Docker, Kubernetes
Rendering Strategies:
- Client-Side Rendering (CSR) - Traditional SPA
- Server-Side Rendering (SSR) - Angular Universal
- Static Site Generation (SSG) - Pre-rendered pages
- Incremental Static Regeneration (ISR) - Hybrid approach
๐ Static Hosting Deployment
Section titled โ๐ Static Hosting DeploymentโNetlify Deployment
Section titled โNetlify Deploymentโ# Install Netlify CLInpm install -g netlify-cli
# Build for productionng build --configuration production
# Deploynetlify deploy --prod --dir=dist/your-app-name/browsernetlify.toml Configuration:
[build] command = "ng build --configuration production" publish = "dist/your-app-name/browser"
[[redirects]] from = "/*" to = "/index.html" status = 200
[build.environment] NODE_VERSION = "20"Vercel Deployment
Section titled โVercel Deploymentโ# Install Vercel CLInpm install -g vercel
# Deployvercel --prodvercel.json Configuration:
{ "buildCommand": "ng build --configuration production", "outputDirectory": "dist/your-app-name/browser", "devCommand": "ng serve", "cleanUrls": true, "trailingSlash": false, "rewrites": [ { "source": "/(.*)", "destination": "/index.html" } ]}GitHub Pages Deployment
Section titled โGitHub Pages Deploymentโ# Install angular-cli-ghpagesng add angular-cli-ghpages
# Build and deployng deploy --base-href=/your-repo-name/GitHub Actions Workflow:
name: Deploy to GitHub Pages
on: push: branches: [ main ]
jobs: deploy: runs-on: ubuntu-latest
steps: - uses: actions/checkout@v3
- name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '20' cache: 'npm'
- name: Install dependencies run: npm ci
- name: Build run: npm run build -- --configuration production --base-href=/your-repo/
- name: Deploy uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./dist/your-app-name/browserโ๏ธ Cloud Platform Deployment
Section titled โโ๏ธ Cloud Platform DeploymentโAWS S3 + CloudFront
Section titled โAWS S3 + CloudFrontโ# Build for productionng build --configuration production
# Install AWS CLI# Upload to S3aws s3 sync dist/your-app-name/browser s3://your-bucket-name --delete
# Invalidate CloudFront cacheaws cloudfront create-invalidation --distribution-id YOUR_DIST_ID --paths "/*"S3 Bucket Policy:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::your-bucket-name/*" } ]}Azure Static Web Apps
Section titled โAzure Static Web Appsโ# Install Azure CLIaz login
# Create static web appaz staticwebapp create \ --name your-app-name \ --resource-group your-resource-group \ --source https://github.com/your-username/your-repo \ --location "East US 2" \ --branch main \ --app-location "/" \ --output-location "dist/your-app-name/browser"staticwebapp.config.json:
{ "navigationFallback": { "rewrite": "/index.html", "exclude": ["/assets/*", "/*.{css,scss,js,png,jpg,jpeg,gif,svg,ico,woff,woff2,ttf,eot}"] }, "routes": [ { "route": "/api/*", "allowedRoles": ["authenticated"] } ], "responseOverrides": { "404": { "rewrite": "/index.html", "statusCode": 200 } }}Google Cloud Platform (Firebase Hosting)
Section titled โGoogle Cloud Platform (Firebase Hosting)โ# Install Firebase CLInpm install -g firebase-tools
# Loginfirebase login
# Initializefirebase init hosting
# Deployfirebase deploy --only hostingfirebase.json:
{ "hosting": { "public": "dist/your-app-name/browser", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "destination": "/index.html" } ], "headers": [ { "source": "**/*.@(jpg|jpeg|gif|png|svg|webp)", "headers": [ { "key": "Cache-Control", "value": "max-age=31536000" } ] }, { "source": "**/*.@(js|css)", "headers": [ { "key": "Cache-Control", "value": "max-age=31536000" } ] } ] }}๐จ Real-World Examples
Section titled โ๐จ Real-World ExamplesโNote: Always test deployments in staging before production.
1. Multi-Environment Deployment
Section titled โ1. Multi-Environment DeploymentโLetโs set up different environments for development, staging, and production.
// angular.json{ "projects": { "your-app": { "architect": { "build": { "configurations": { "development": { "optimization": false, "sourceMap": true, "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.development.ts" } ] }, "staging": { "optimization": true, "outputHashing": "all", "sourceMap": false, "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ] }, "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "budgets": [ { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" } ], "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.production.ts" } ] } } } } } }}Environment Files:
export const environment = { production: false, apiUrl: 'http://localhost:3000/api', enableDebug: true};
// environment.staging.tsexport const environment = { production: false, apiUrl: 'https://staging-api.example.com/api', enableDebug: true};
// environment.production.tsexport const environment = { production: true, apiUrl: 'https://api.example.com/api', enableDebug: false};2. Automated Deployment Script
Section titled โ2. Automated Deployment ScriptโLetโs create a deployment script with pre-deployment checks.
#!/bin/bashset -e
echo "๐ Starting deployment process..."
# Check if on correct branchBRANCH=$(git branch --show-current)if [ "$BRANCH" != "main" ]; then echo "โ Error: Must be on main branch to deploy" exit 1fi
# Check for uncommitted changesif [ -n "$(git status --porcelain)" ]; then echo "โ Error: Uncommitted changes detected" exit 1fi
# Run testsecho "๐งช Running tests..."npm run test:ci
# Run lintingecho "๐ Running linter..."npm run lint
# Build for productionecho "๐ฆ Building for production..."npm run build -- --configuration production
# Check bundle sizeecho "๐ Checking bundle size..."npm run analyze
# Deployecho "๐ Deploying to production..."case "$1" in netlify) netlify deploy --prod --dir=dist/your-app/browser ;; vercel) vercel --prod ;; firebase) firebase deploy --only hosting ;; *) echo "Usage: ./deploy.sh [netlify|vercel|firebase]" exit 1 ;;esac
echo "โ
Deployment complete!"3. Progressive Web App (PWA) Deployment
Section titled โ3. Progressive Web App (PWA) DeploymentโLetโs configure PWA deployment with service worker.
# Add PWA supportng add @angular/pwangsw-config.json:
{ "$schema": "./node_modules/@angular/service-worker/config/schema.json", "index": "/index.html", "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**", "/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)" ] } } ], "dataGroups": [ { "name": "api", "urls": [ "https://api.example.com/**" ], "cacheConfig": { "maxSize": 100, "maxAge": "1h", "timeout": "10s", "strategy": "freshness" } } ]}โ Best Practices
Section titled โโ Best Practicesโ1. Use Environment Variables
Section titled โ1. Use Environment Variablesโ// โ
Good - Use environment filesimport { environment } from './environments/environment';
const apiUrl = environment.apiUrl;
// โ Avoid - Hardcoded valuesconst apiUrl = 'https://api.example.com';2. Enable Production Mode
Section titled โ2. Enable Production Modeโimport { enableProdMode } from '@angular/core';import { environment } from './environments/environment';
if (environment.production) { enableProdMode();}3. Configure Caching Headers
Section titled โ3. Configure Caching Headersโlocation ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable";}
location / { try_files $uri $uri/ /index.html; add_header Cache-Control "no-cache";}4. Use CDN for Assets
Section titled โ4. Use CDN for Assetsโ// angular.json{ "projects": { "your-app": { "architect": { "build": { "configurations": { "production": { "deployUrl": "https://cdn.example.com/" } } } } } }}5. Monitor Deployments
Section titled โ5. Monitor Deploymentsโimport { environment } from './environments/environment';
if (environment.production) { // Initialize error tracking Sentry.init({ dsn: 'your-sentry-dsn', environment: 'production' });
// Initialize analytics gtag('config', 'GA_MEASUREMENT_ID');}๐ฏ Deployment Checklist
Section titled โ๐ฏ Deployment Checklistโ- Run tests before deployment
- Build with production configuration
- Check bundle sizes
- Test in staging environment
- Configure environment variables
- Set up proper caching headers
- Enable HTTPS
- Configure CDN
- Set up monitoring and analytics
- Create rollback plan
๐ Learning Checklist
Section titled โ๐ Learning Checklistโ- Understand different hosting options
- Configure production builds
- Set up environment files
- Deploy to static hosting
- Deploy to cloud platforms
- Configure caching strategies
- Implement PWA features
- Set up monitoring
๐ Next Steps
Section titled โ๐ Next Stepsโ- Docker & Containers - Containerize your application
- CI/CD Pipelines - Automate deployments
- Performance Optimization - Optimize before deploying
Pro Tip: Always use a staging environment that mirrors production! Test deployments thoroughly before going live. Use automated deployment scripts to ensure consistency! ๐