Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 74 ยท Tooling and Ecosystem

Building and Deploying

Build an Angular app for production with ng build, understand the output, budgets and environments, host it as static files with SPA fallback and caching, and automate it with Docker and CI.

During development ng serve gives you fast rebuilds and readable errors. A production build does the opposite: it spends time to make the smallest, fastest files it can. Then you put those files somewhere users can reach them. For a client-side Angular app, that "somewhere" can be almost any static host, because the result is just HTML, JavaScript and CSS.

This lesson covers ng build, what ends up in the output folder, size budgets, environment-specific settings, the one hosting rule every single-page app needs (the index fallback), caching, and outlines for a Docker image and a CI pipeline. Apps with server-side rendering need a Node server instead, which SSR, Hydration and Prerendering covers.

Real versus stand-in. The bash, json, nginx, dockerfile and yaml blocks are real configuration to read, because the site cannot run the Angular CLI, a web server or Docker. The runnable examples are plain TypeScript stand-ins: a budget checker and a static host that decides which file to serve. Exact numbers and defaults vary by Angular version, so check your own angular.json.

ng build

Terminal
ng build

Since Angular 12 the default configuration of ng build is production: ahead-of-time compilation, minification, tree shaking (removing unused code), dead code elimination and content-hashed file names. A new project's angular.json also has a development configuration with optimization off and source maps on:

Terminal
ng build --configuration development

Current projects use the application builder, based on esbuild and Vite, which is also what powers ng serve. It produces a folder under dist/:

TEXT
dist/my-app/
  browser/
    index.html
    main-5CZ6NQPF.js        your code, with a hash in the name
    chunk-7XJ2K4LM.js       lazy-loaded route and shared chunks
    styles-3QWE8TYU.css
    favicon.ico
    media/                  fonts and other imported assets
  3rdpartylicenses.txt

The hash in a file name comes from its content. If the file changes, the name changes, so browsers and CDNs can cache hashed files for a very long time and still pick up new releases, because the new index.html points to new names. The browser folder is what you deploy. When SSR is enabled, a sibling server folder holds the Node server too.

flowchart LR
  S["Source<br/>TypeScript, templates, styles"] --> C["Angular compiler (AOT)"]
  C --> B["esbuild<br/>bundle, tree-shake, minify, split"]
  B --> O["dist/app/browser<br/>hashed files + index.html"]
  O --> H["Static host or CDN"]
  H --> U["User's browser"]

A production build compiles templates ahead of time, bundles and optimizes, and writes hashed files you can host anywhere.

Budgets: stop bundles from growing silently

Bundles tend to grow one dependency at a time. Budgets in angular.json make the build warn or fail when a size limit is crossed, so growth becomes a visible decision:

JSON
"budgets": [
  { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" },
  { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }
]

initial is everything the first page load needs (the main bundle plus the chunks it imports eagerly). anyComponentStyle limits a single component's stylesheet. Those numbers are common defaults; set limits that fit your own app and tighten them over time. Lazy chunks are not part of the initial budget, which is one more reason to split routes (Child Routes and Lazy Loading); more tuning ideas are in Performance Tuning.

A budget check is a simple comparison, and the stand-in shows it. For simplicity it treats kB as 1,024 bytes; read your Angular version's documentation for its exact rule.

TypeScript A bundle budget checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Environments and configuration

Apps often need different values per environment: an API base URL, a feature flag, an analytics key. Generate the files with:

Terminal
ng generate environments

This creates src/environments/environment.ts (production values) and environment.development.ts, and adds fileReplacements to the development configuration so the right file is swapped in at build time:

TypeScript
// src/environments/environment.ts
export const environment = {
  production: true,
  apiUrl: 'https://api.example.com',
};
TypeScript
import { environment } from '../environments/environment';

http.get(`${environment.apiUrl}/products`);

Anything in these files is bundled into public JavaScript, so never put secrets in them. API keys that must stay private belong on a server. Another consequence of compile-time environments is that you need a separate build for each value. If one build must run in several environments (staging, production), load a small config.json at startup instead, for example with provideAppInitializer(), and keep the build identical everywhere.

Two useful options: --base-href /app/ for an app served from a sub-path, and --stats-json to write a file you can feed to a bundle analyzer.

Hosting static files

Because the output is static, you can serve it from an object store with a CDN, from Netlify, Vercel, Firebase Hosting, GitHub Pages, nginx, Apache or any other file server. Every host needs two rules:

  1. Index fallback. Angular's router handles URLs like /products/42 in the browser. When someone opens or refreshes that URL, the server receives a request for /products/42, which is not a file. The server must answer with index.html so the router can start. Without that rule, refresh gives 404.
  2. Caching. Hashed files can be cached for a year. index.html must not be cached for long, because it is the file that names the current hashed files.
NGINX
server {
  listen 80;
  root /usr/share/nginx/html;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }

  location = /index.html {
    add_header Cache-Control "no-cache";
  }

  location ~* \.(?:js|css|woff2)$ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    try_files $uri =404;
  }

  gzip on;
  gzip_types text/css application/javascript image/svg+xml;
}

Look at the last location: a missing .js file returns a real 404 instead of the fallback page, which prevents the confusing error where a script request gets HTML back. The stand-in below applies the same decisions in TypeScript.

TypeScript A static host with SPA fallback and cache headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A Docker image

A multi-stage Dockerfile builds in one image with Node and serves from a small nginx image. Only the built files reach the final image:

DOCKERFILE
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx ng build

FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist/my-app/browser /usr/share/nginx/html
EXPOSE 80

Copying package.json and running npm ci before copying the source lets Docker reuse the dependency layer when only your code changes. Pick a Node version that your Angular version supports. The project name in the path (my-app) must match your angular.json.

Continuous integration

A minimal pipeline installs exactly what the lockfile says, lints, tests once without a watcher and builds. Here is a GitHub Actions example:

YAML
name: ci
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npx ng lint
      - run: npx ng test --no-watch
      - run: npx ng build

How you run tests headlessly depends on the test runner your project uses (Testing Components and Services); check its documentation for the right flags. Because budgets fail the build, a bundle regression turns the pipeline red. From there, deploying is a copy of dist/.../browser to your host, or pushing the image to a registry.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do production builds put a hash in file names?

    The hash comes from the content. When the content changes, the name changes, so long-lived caching is safe.
  2. 2. A user refreshes /products/42 on your static host and gets 404. What is missing?

    The server has no file at that path. Serving index.html lets the Angular router start and handle the URL.
  3. 3. What is a build budget?

    Budgets turn bundle growth into a visible warning or a failing build, so size regressions are noticed early.
  4. 4. Which statement about environment.ts files is correct?

    They are compiled into the bundle that every user downloads. Keep secrets on a server.
  5. 5. Why should index.html not be cached for a long time?

    index.html is the entry point that names the hashed bundles. If it is cached too long, users do not see new releases.

Summary

  • ng build produces an optimized, content-hashed build in dist/<project>/browser; --configuration development skips optimization.
  • Budgets in angular.json warn or fail when bundles grow past a limit.
  • Environment files are compiled into public JavaScript: no secrets, and load a runtime config if one build must serve several environments.
  • A single-page app needs an index fallback for unknown paths, long caching for hashed files and no long caching for index.html.
  • A multi-stage Dockerfile (Node to build, nginx to serve) and a short CI pipeline (npm ci, lint, test, build) automate delivery.

Next: Project: Todo App with Signals.