Angular Deployment

Deployment is the process of taking the Angular application from the development environment and making it available on the internet for users to access. A development application running on localhost:4200 must be compiled into optimized static files and then published to a web server or hosting platform.

Angular's build process transforms TypeScript, HTML, and CSS into plain JavaScript, HTML, and CSS files that any browser can understand, with all Angular framework code included in the output.

Understanding the Production Build

The production build is the compiled, optimized version of the application ready for deployment. Run it with:


ng build --configuration production

This command produces a dist/ folder with all the files needed to run the application. The production build automatically applies several optimizations:

Ahead-of-Time (AOT) Compilation

Angular's templates are compiled from HTML to JavaScript during the build process rather than in the browser at runtime. This results in smaller bundles, faster rendering, and earlier template error detection.

Tree Shaking

The build process analyzes which code is actually used and removes all unused code from the bundle. If a library exports 100 functions but the application only uses 5, only those 5 are included in the final build.

Minification

All JavaScript and CSS files are minified — whitespace, comments, and long variable names are removed or shortened to reduce file size.

Bundle Splitting

The application code is split into multiple chunk files. The main bundle contains the core application. Lazy-loaded modules produce separate chunk files that are only downloaded when needed.

The dist/ Folder Structure


dist/
└── my-app/
    ├── index.html              ← Main HTML file
    ├── main.abc123.js          ← Application code bundle
    ├── polyfills.def456.js     ← Browser compatibility code
    ├── runtime.ghi789.js       ← Angular runtime
    ├── styles.css              ← Global styles
    └── assets/                 ← Images, fonts, and other static files
        └── images/

The hash values in filenames (e.g., abc123) change every time the code changes. This technique is called cache busting — it ensures browsers always download the latest version rather than serving outdated cached files.

Configuring Base Href

If the application is deployed in a subfolder (not the root of the domain), the base href must be set accordingly. For example, deploying to https://example.com/my-app/:


ng build --configuration production --base-href /my-app/

For deployment at the root domain (https://example.com/), no base href configuration is needed.

Deploying to Different Platforms

Option 1 — Firebase Hosting (Recommended for Beginners)

Firebase Hosting by Google is one of the simplest options for hosting Angular applications. It provides a free tier, a global CDN, HTTPS by default, and easy CLI deployment.


// Step 1: Install Firebase CLI globally
npm install -g firebase-tools

// Step 2: Log in to Firebase
firebase login

// Step 3: Initialize Firebase in the project
firebase init

// During initialization:
// - Select "Hosting"
// - Choose the Firebase project
// - Set public directory to: dist/my-app
// - Configure as single-page app: Yes
// - Overwrite index.html: No

// Step 4: Build the application
ng build --configuration production

// Step 5: Deploy
firebase deploy

After deployment, Firebase provides a URL like https://my-app.web.app where the application is live.

Option 2 — Netlify

Netlify offers continuous deployment directly from a Git repository. Any push to the main branch automatically triggers a new build and deployment.


// Step 1: Install Netlify CLI
npm install -g netlify-cli

// Step 2: Build the application
ng build --configuration production

// Step 3: Deploy
netlify deploy --dir=dist/my-app --prod

Alternatively, connect the GitHub repository on the Netlify website and configure these settings:

  • Build command: ng build --configuration production
  • Publish directory: dist/my-app

Option 3 — GitHub Pages

GitHub Pages is a free hosting option provided by GitHub for repositories. Angular CLI includes a built-in command for GitHub Pages deployment via the angular-cli-ghpages package:


// Step 1: Install the GitHub Pages deployment package
ng add angular-cli-ghpages

// Step 2: Build and deploy in one command
ng deploy --base-href=/repository-name/

Option 4 — AWS S3 + CloudFront

For production-grade deployments, AWS S3 (Simple Storage Service) hosts the static files and CloudFront (CDN) delivers them globally with low latency. This is a more complex setup but offers excellent scalability and performance.


// Step 1: Build the application
ng build --configuration production

// Step 2: Install AWS CLI and configure credentials
aws configure

// Step 3: Sync the dist folder to an S3 bucket
aws s3 sync dist/my-app s3://my-bucket-name --delete

// Step 4: Set cache headers
aws s3 cp dist/my-app/index.html s3://my-bucket-name/index.html \
  --cache-control "no-cache, no-store, must-revalidate"

aws s3 cp dist/my-app s3://my-bucket-name \
  --recursive \
  --exclude "index.html" \
  --cache-control "max-age=31536000"

The index.html file uses no-cache to ensure the browser always gets the latest version. All other files (JS, CSS) use long cache times because their filenames change with each build due to hashing.

Option 5 — Traditional Web Server (Nginx/Apache)

The production build is just static files. Any web server (Nginx, Apache, IIS) can serve them.


// Copy the dist folder to the web server's public directory
scp -r dist/my-app/* user@server.com:/var/www/html/
Important: SPA Redirect Configuration

Since Angular is a single-page application, all URL routing is handled by Angular — not the server. If a user directly accesses https://example.com/products, the server must serve index.html and let Angular handle the routing. Without this configuration, the server returns a 404 error.

Nginx configuration:


server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
        # If the file doesn't exist, serve index.html instead
    }
}

Apache .htaccess configuration:


RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Environment Configuration

Angular projects include environment files for separating development and production settings — such as API base URLs, feature flags, and API keys.


src/environments/
├── environment.ts          ← Development settings
└── environment.prod.ts     ← Production settings

// environment.ts (development)
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000/api',
  enableDebugLogs: true
};

// environment.prod.ts (production)
export const environment = {
  production: true,
  apiUrl: 'https://api.myapp.com/api',
  enableDebugLogs: false
};

// Using environment variables in a service
import { environment } from '../../environments/environment';

@Injectable({ providedIn: 'root' })
export class ApiService {
  private baseUrl = environment.apiUrl;   // Automatically uses correct URL

  getUsers() {
    return this.http.get(`${this.baseUrl}/users`);
  }
}

During a production build, Angular automatically replaces environment.ts with environment.prod.ts — no code changes are needed.

Deployment Checklist


Before deploying:
□ Run ng build --configuration production successfully
□ Test the production build locally: npx serve -s dist/my-app
□ Verify environment variables point to production APIs
□ Check browser console for errors in production build
□ Confirm all lazy-loaded routes work correctly
□ Verify 404 redirect to index.html is configured on the server
□ Enable HTTPS on the hosting platform
□ Check bundle sizes are acceptable

Summary

Deploying an Angular application involves running ng build --configuration production to generate optimized static files in the dist/ folder. The production build applies AOT compilation, tree shaking, minification, and bundle splitting. These static files can be hosted on Firebase Hosting, Netlify, GitHub Pages, AWS S3, or any traditional web server. Single-page applications require the server to redirect all routes back to index.html, allowing Angular's router to handle navigation. Environment files (environment.ts and environment.prod.ts) separate development and production configuration. The production build automatically uses the correct environment file, keeping sensitive settings out of development code.

Leave a Comment

Your email address will not be published. Required fields are marked *