Skip to main content

Angular Azure Deployment

Introduction

Deploying an Angular application to Microsoft Azure is a popular choice for many developers and organizations due to Azure's robust infrastructure, scalability options, and integration with various developer tools. This guide will walk you through the process of deploying your Angular application to Azure, covering everything from basic setup to advanced configuration options.

Azure offers several hosting options for Angular applications, including:

  • Azure Static Web Apps: Ideal for static web applications like Angular
  • Azure App Service: A fully managed platform for web applications
  • Azure Storage: Cost-effective hosting for static content
  • Azure Container Instances or Azure Kubernetes Service: For containerized deployments

In this tutorial, we'll focus on the two most common approaches: Azure Static Web Apps and Azure App Service.

Prerequisites

Before we begin, make sure you have:

  • An Angular application ready for deployment
  • Node.js and npm installed
  • Azure account (you can create a free account at azure.microsoft.com)
  • Azure CLI installed (npm install -g @azure/cli)
  • Git installed

Deploying to Azure Static Web Apps

Azure Static Web Apps is a service that automatically builds and deploys web apps from a GitHub repository. It's perfect for Angular applications as it handles the build process and provides a global CDN.

Step 1: Prepare Your Angular Application

Ensure your Angular application is ready for production. Run the following command to build your app:

bash
ng build --prod

This will create a dist/ folder containing your compiled application.

Step 2: Push Your Code to GitHub

If your project isn't already in a GitHub repository, create one and push your code:

bash
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/your-angular-app.git
git push -u origin main

Step 3: Create an Azure Static Web App

  1. Log in to the Azure Portal

  2. Click on "Create a resource"

  3. Search for "Static Web App" and select it

  4. Click "Create"

  5. Fill in the basic details:

    • Resource Group: Create new or select existing
    • Name: Your app name
    • Region: Choose the closest to your users
    • SKU: Standard (or Free for testing)
  6. Connect to your GitHub repository:

    • Select your GitHub account
    • Select your repository
    • Select your branch (e.g., main)
  7. In the Build Details section:

    • Build Preset: Angular
    • App location: /
    • Output location: dist/your-app-name (replace with your actual app name)
  8. Click "Review + Create" and then "Create"

Azure will now set up a GitHub Actions workflow in your repository and deploy your application automatically.

Step 4: Monitor the Deployment

You can monitor the deployment process in two places:

  1. In the Azure Portal under your Static Web App resource
  2. In your GitHub repository under the Actions tab

Once deployed, you can access your application using the URL provided in the Azure Portal.

Example: Configuration for Azure Static Web Apps

Here's an example of the GitHub Actions workflow file that Azure creates in your repository (.github/workflows/azure-static-web-apps.yml):

yaml
name: Azure Static Web Apps CI/CD

on:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened, closed]
branches:
- main

jobs:
build_and_deploy_job:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
name: Build and Deploy Job
steps:
- uses: actions/checkout@v2
with:
submodules: true
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
repo_token: ${{ secrets.GITHUB_TOKEN }}
action: "upload"
app_location: "/"
api_location: "api"
output_location: "dist/your-angular-app"

This workflow automatically builds and deploys your application whenever you push changes to your main branch.

Deploying to Azure App Service

Azure App Service is a fully managed platform for building, deploying, and scaling web applications. It's suitable for more complex applications or those needing server-side capabilities.

Step 1: Prepare Your Angular Application

Build your Angular application:

bash
ng build --prod

Step 2: Set Up an Azure Web App

  1. Log in to the Azure CLI:
bash
az login
  1. Create a resource group (if you don't already have one):
bash
az group create --name myResourceGroup --location "East US"
  1. Create an App Service plan:
bash
az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku B1
  1. Create a web app:
bash
az webapp create --name my-angular-app --resource-group myResourceGroup --plan myAppServicePlan

Step 3: Configure the Web App

Configure your web app for static site hosting:

bash
az webapp config set --name my-angular-app --resource-group myResourceGroup --startup-file "index.html"

Step 4: Deploy Your App

There are multiple ways to deploy your app to Azure App Service:

Option 1: Deploy using the Azure CLI

bash
az webapp deployment source config-local-git --name my-angular-app --resource-group myResourceGroup

This gives you a Git URL. Add it as a remote and push your code:

bash
git remote add azure <git-url-from-previous-command>
git push azure main

Option 2: Deploy using ZIP Deploy

bash
cd dist/your-angular-app
zip -r ../app.zip *
az webapp deployment source config-zip --resource-group myResourceGroup --name my-angular-app --src ../app.zip

Step 5: Configure Routes for Angular's Client-Side Routing

For Angular's client-side routing to work properly, you need to add a web.config file in your project's src folder:

xml
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

Then update your angular.json to include this file in the build:

json
"assets": [
"src/favicon.ico",
"src/assets",
"src/web.config"
]

Setting Up Continuous Deployment

Using GitHub Actions for Azure App Service

  1. Create a GitHub Actions workflow file in .github/workflows/main.yml:
yaml
name: Build and deploy Angular app to Azure Web App

on:
push:
branches:
- main

jobs:
build-and-deploy:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '16.x'

- name: Install dependencies
run: npm ci

- name: Build
run: npm run build -- --prod

- name: Deploy to Azure Web App
uses: azure/webapps-deploy@v2
with:
app-name: 'my-angular-app'
publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
package: ./dist/your-angular-app
  1. In the Azure Portal, navigate to your App Service, go to "Deployment Center" > "Manage publish profile" and download the publish profile.

  2. In your GitHub repository, go to Settings > Secrets and add a new secret named AZURE_WEBAPP_PUBLISH_PROFILE with the content of the downloaded file.

Real-world Example: Deploying an Angular E-commerce App to Azure

Let's walk through a practical example of deploying an e-commerce Angular application to Azure Static Web Apps with environment-specific configurations.

Step 1: Set Up Environment Configurations

Create environment-specific files:

src/environments/environment.ts:

typescript
export const environment = {
production: false,
apiUrl: 'http://localhost:3000/api',
stripeKey: 'pk_test_YOUR_TEST_KEY'
};

src/environments/environment.prod.ts:

typescript
export const environment = {
production: true,
apiUrl: 'https://api.yourproductionsite.com/api',
stripeKey: 'pk_live_YOUR_LIVE_KEY'
};

Step 2: Create Routes Configuration

For our e-commerce app, we need several routes:

app-routing.module.ts:

typescript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProductListComponent } from './products/product-list.component';
import { ProductDetailComponent } from './products/product-detail.component';
import { CartComponent } from './cart/cart.component';
import { CheckoutComponent } from './checkout/checkout.component';

const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', component: ProductListComponent },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: 'cart', component: CartComponent },
{ path: 'checkout', component: CheckoutComponent },
{ path: '**', redirectTo: '' }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Step 3: Create a Custom Build Script

Add this to your package.json:

json
"scripts": {
"build:prod": "ng build --configuration=production",
"build:staging": "ng build --configuration=staging"
}

Step 4: Configure Azure Static Web Apps with API Integration

Create a file at api/products/index.js for backend functionality:

javascript
module.exports = async function (context, req) {
context.res = {
body: [
{ id: 1, name: "Product 1", price: 19.99 },
{ id: 2, name: "Product 2", price: 29.99 },
{ id: 3, name: "Product 3", price: 39.99 }
],
headers: {
'Content-Type': 'application/json'
}
};
};

Update your GitHub workflow to include the API folder:

yaml
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
repo_token: ${{ secrets.GITHUB_TOKEN }}
action: "upload"
app_location: "/"
api_location: "api"
output_location: "dist/your-angular-app"

Step 5: Set Up Environment Variables in Azure

In the Azure Portal, go to your Static Web App > Configuration and add:

  1. STRIPE_KEY: Your Stripe public key
  2. API_URL: Your backend API URL

Then access these in your Angular app through an API function:

typescript
// src/app/services/config.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class ConfigService {
constructor(private http: HttpClient) {}

getConfig(): Observable<any> {
return this.http.get('/api/config');
}
}

Common Issues and Troubleshooting

1. Routing Issues

Problem: 404 errors when refreshing on routes other than the home page.

Solution: Ensure you've configured proper URL rewriting as described earlier with the web.config file or Azure Static Web Apps' routes.json:

json
{
"routes": [
{
"route": "/*",
"serve": "/index.html",
"statusCode": 200
}
]
}

2. Environment Variables

Problem: Unable to access environment variables.

Solution: For Azure App Service, use Application Settings. For Azure Static Web Apps, use the Configuration section or API functions to expose them.

3. API Communication

Problem: CORS issues when calling APIs.

Solution: Set up CORS properly in your API settings:

bash
az webapp cors add --name my-angular-app --resource-group myResourceGroup --allowed-origins 'https://your-frontend-url.com'

Summary

In this guide, we've covered:

  1. Deploying Angular applications to Azure Static Web Apps
  2. Deploying to Azure App Service
  3. Setting up continuous deployment with GitHub Actions
  4. Configuring client-side routing in Azure
  5. Managing environment-specific configurations
  6. A real-world e-commerce application deployment example
  7. Troubleshooting common issues

Azure provides a robust and flexible platform for hosting Angular applications, with options suited for different types of projects, from simple static sites to complex enterprise applications.

Additional Resources

Exercises

  1. Deploy a simple Angular todo app to Azure Static Web Apps.
  2. Set up continuous deployment for your Angular application using GitHub Actions and Azure App Service.
  3. Create an Angular application that uses environment variables for different deployment environments (dev, staging, production).
  4. Implement a custom domain and SSL certificate for your Azure-hosted Angular application.
  5. Set up Azure Application Insights to monitor your Angular application's performance and usage.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)