Azure App Services

What is Azure App Service?

  • It is an HTTP-based service (PaaS) to host web applications, REST APIs, and back-ends.

  • It supports .NET, .NET Core, Java, Python, NodeJs and PHP.

  • It supports autoscaling to adjust to request loads on both Windows and Linux.

  • It also supports Azure security, load balancing, and automated deployment.

  • We can containerize the app and host a custom Windows or Linux container in App Service.

  • It supports Azure Functions.

  • It also supports dedicated tools in Visual Studio and Visual Studio Code to streamline the work of creating, deploying, and debugging.

  • It supports deployment slots which are live apps with their own host names , app content and configurations that can be swapped.

Limitations

  • Linux is not supported on shared tier.

  • You cant mix Windows and Linux apps in the same app service.

  • Can’t install 3rd party tools/software unlike VMs.

  • Use Kudu console/portal to view logs and events.

App Service Plan

An App Service Plan defines the region, features, and pricing tier for hosting.

It includes OS, Region, Pricing tier, No of and size of VM instances. One or more apps can be deployed that will share the same app service plan(same compute resources).\

Different pricing tiers are available which determines the features according to the price.

  • Shared compute (Free and Shared): Apps runs on same VM shared by others and doesn’t support scaling.

  • Dedicated compute (Basic, Standard, Premium, PremiumV2, and PremiumV3): Apps runs on dedicated VMs. Only apps in the same App Service Plan share the same compute resources.

  • Isolated (Isolated and IsolatedV2): Apps run on dedicated Azure VMs on dedicated Azure Virtual Networks. It provides network isolation on top of compute isolation to your apps.

  • Consumption: Only available to Function apps. It scales the functions dynamically depending on workload.

How does app run and scale?

  • An app runs on all the VM instances configured in the App Service plan.

  • If multiple apps are in the same App Service plan, they all share the same VM instances.

  • If you have multiple deployment slots for an app, all deployment slots also run on the same VM instances.

  • If you enable diagnostic logs, perform backups, or run Web Jobs, they also use CPU cycles and memory on these VM instances.

Authentication in App Service

App Service supports built-in authentication, using it you can integrate with multiple login providers.

Deploy an app (ZIP package) to App Service(Web App)

We can create a project or use any existing project to publish and deploy.

//create an azure web app under any resource group and deploy
//create a new project using VS or use an existing project
dotnet new webapp -o az-practice-app 
//publish the project
dotnet publish -o publish
//compress the publish folder
compress-Archive * publish.zip

Now we can use Azure CLI to create resources and deploy the app.

//login to azure
az login
//create resource group
az group create --location eastus2 --resource-group az-practice
//create app service plan under a resource group
az appservice plan create -g az-practice -n az-practice-plan --sku FREE
//create web app
az webapp create -g az-practice -p az-practice-plan -n az-practice-app
//deploy to web app
az webapp deployment source config-zip --src.\publish.zip -n az-practice-app -g az-practice

Deploy an app from a local workspace to the app to App Service (Web App)

We can use “az webapp up” command to deploy from local workspace. It deploys to existing webapp or creates a new one if it doesn’t exist (also creates app service plan if it doesn’t exist). This command also zips the content and deploy the package

mkdir htmlapp
cd htmlapp
git clone https://github.com/Azure-Samples/html-docs-hello-world.git

//create resource group
az group create --location eastus2 --resource-group az-practice

//get in to the code folder
cd html-docs-hello-world

//deploy using 
az webapp up -g az-practice -n helloworldapp --html

Networking Features

Azure App Service is a distributed system. The parts that manage incoming HTTP or HTTPS requests are called front ends. The parts that run the customer's applications are called workers. All components in an App Service deployment are part of a multi-tenant network. Since many different customers share the same App Service scale unit, you cannot directly connect the App Service network to your own network.

Instead of connecting the networks, you need features to manage different aspects of application communication.

To ensure seamless communication and security, Azure App Service supports a variety of inbound and outbound features. These features facilitate the flow of data into and out of your applications while enabling you to maintain high performance and security standards.

Inbound Features:

  • App-assigned address - It provides a static inbound IP address for your application. This feature is particularly useful in scenarios where external systems need to consistently interact with your app and rely on a static IP for routing or security purposes.

  • Access restrictions

  • Service endpoints

  • Private endpoints

Outbound Features:

  • Hybrid Connections

  • Gateway-required virtual network integration

  • Virtual network integration

FeatureInboundOutbound
FocusTraffic entering your App ServiceTraffic leaving your App Service
SecurityIP restrictions, SSL/TLS, AuthenticationManaged Identity, VNET, Firewalls
RoutingDNS, Traffic Manager, URL RewriteDNS, Virtual Network Integration, Hybrid Connections
ScalingLoad balancing, AutoscalingConnection scaling, Outbound IP pools
Unique FeaturesApp-Assigned Address, Private EndpointsHybrid Connections, Gateway-Required VNET Integration

Inbound Use Cases

  • App-Assigned Address provides a static inbound IP that can be whitelisted.

  • Custom domains secured with SSL/TLS for safe access.

  • Azure Traffic Manager for distributing traffic globally.

  • Autoscaling to accommodate sudden increases in traffic.

  • Authentication and Authorization (e.g., OAuth through Azure AD).

  • IP restrictions to permit traffic exclusively from designated sources.

  • URL rewriting for a more straightforward and organized API structure.

  • Private Endpoints to limit access to internal IP addresses.

  • App Service Environment (ASE) for a secluded deployment where deployment of Azure App Service is done into a subnet in a customer's Azure Virtual Network instance.

  • Web Application Firewall (WAF) to prevent harmful requests.

  • Azure Traffic Manager with geographic routing capabilities.

  • Autoscaling to boost resources in regions experiencing high demand.

Outbound Use Cases

  • Virtual Network Integration for secure database access.

  • Service Endpoints to keep traffic on Azure's private backbone.

  • Hybrid Connections for secure and lightweight communication.

  • Outbound IP addresses for consistent API whitelisting.

  • Custom DNS for resolving external API endpoints.

  • Managed Identity to authenticate without credentials.

  • VNET Integration for secure communication with Key Vault.

  • Outbound connections to messaging services like service bus and event grid.

  • Application Insights to monitor event delivery.

  • Service Endpoints for secure service-to-service communication.

  • Outbound firewall rules to restrict external communication.

  • Custom DNS for multi-cloud name resolution in multi-cloud integration scenario.

  • Outbound IP control for integration security.

  • Outbound traffic to CDN endpoints.

  • Connection scaling to handle high outbound data transfer.

Configure Environment Variables

Application settings in Azure App Service let you define and manage key-value pairs that your app can use while running. These include configuration values like database connection strings, API keys, and feature flags.

It also consists of slot settings. Settings that are sticky to a specific deployment slot. For example, a staging slot may use different settings from the production slot.

Benefits of Application Settings

  1. Separation of Concerns:

    • Keep environment-specific data (like connection strings) separate from the application code.
  2. Security:

    • Safeguard sensitive information by avoiding hardcoding secrets into the codebase.

    • Environment variables are always encrypted when stored.

  3. Flexibility:

    • Update configuration values without needing to redeploy the app.
  4. Slot Independence:

    • Allow different settings for various deployment slots (e.g., production, staging, or testing).

Best Practices

1. Utilize Azure Key Vault for Sensitive Data

  • For highly sensitive information such as secrets or certificates, use Azure Key Vault and integrate it with your App Service.

2. Designate Environment-Specific Settings as Slot Settings

  • Identify settings as Deployment slot settings to ensure that changes in one slot (e.g., staging) do not impact another (e.g., production).

Commonly used CLI commands

//List Application Settings
az webapp config appsettings list --name MyApp --resource-group MyResourceGroup
//Add or Update Application Settings
az webapp config appsettings set --name <AppName> --resource-group <ResourceGroup> --settings <Key1>=<Value1> <Key2>=<Value2>
//Remove Application Settings
az webapp config appsettings delete --name MyApp --resource-group MyResourceGroup --setting-names API_KEY OLD_SETTING

//List Connection Strings
az webapp config connection-string list --name <AppName> --resource-group <ResourceGroup>
//Add or Update Connection Strings
az webapp config connection-string set --name MyApp --resource-group MyResourceGroup --settings DefaultConnection="Server=myserver.database.windows.net;Database=mydb;User=myuser;Password=mypassword;" --connection-string-type SQLAzure
//Remove Connection Strings
az webapp config connection-string delete --name MyApp --resource-group MyResourceGroup --setting-names DefaultConnection

//Enable or Disable Slot Settings
az webapp config appsettings set --name <AppName> --resource-group <ResourceGroup> --slot-settings <Key1>=<Value1>

Configure General Settings

General settings in Azure App Service let you control application runtime environments, platform configurations, and other key operational parameters, allowing you to customize your app's behavior, optimize performance, and ensure compatibility with your development framework.

  1. Platform Settings

    • Operating System: Windows or Linux

    • Platform bitness: 32-bit or 64-bit. For Windows apps only.

    • FTP state: Allow only FTPS or disable FTP altogether.

    • HTTP version: Set to 2.0 to enable support for HTTPS/2 protocol.

    • Web sockets

    • Always On: Ensures the application remains active even in the absence of traffic. By default, if Always On is not enabled, the application is unloaded after 20 minutes of inactivity, which can lead to increased latency for new requests due to the warm-up period. When Always On is enabled, the front-end load balancer sends a GET request to the application root every five minutes, maintaining the application's active state and preventing it from being unloaded.

    • ARR Affinity: In a multi-instance deployment, this setting ensures that the client is consistently routed to the same instance throughout the session. For stateless applications, you may choose to set this option to Off.

    • HTTPS Only: When enabled, all HTTP traffic is redirected to HTTPS.

    • Minimum TLS Version: Choose the minimum TLS encryption version required by your application.

2. Runtime Stack - The software stack to run the app, including the language and SDK versions. For Linux apps and custom container apps, you can also set an optional start-up command or file.

3. Debugging: Enable remote debugging for applications. This feature automatically disables after 48 hours.

4. Incoming Client Certificates: Require client certificates for mutual authentication. TLS mutual authentication is utilized to restrict access to your application by enabling various authentication methods.

Configure Path Mappings

Path mappings in Azure App Service enable routing of requests to specific directories, files, or application components. This feature is especially beneficial for applications needing access to custom scripts, static content, or configuration files stored in various locations. Properly configuring path mappings can enhance application performance, organization, and scalability.

Use Cases

  • Serving static files.

  • Accessing shared configuration files or libraries.

  • Redirecting requests to specific endpoints.

  • Integrating external storage.

For Windows applications, you have the option to customize IIS handler mappings as well as virtual applications and directories.

Example:

  • **Virtual Path: The route you want to define (e.g., /static, /home).

  • Physical Path: The actual directory path in your app's file system (e.g., wwwroot/static).

  • Application: Indicate if this is a standalone application or part of the primary app.

For Linux and containerized apps(including Windows), you can mount Azure Storage to access and serve content directly from Azure Blob Storage or Azure Files.

Configure Error pages

You can configure a custom HTML document to be displayed to users in place of the default platform error page.

Autoscaling

Autoscaling is a process that adjusts available resources based on current demand. It performs scaling in and out, as opposed to up and down.

Autoscaling responds to changes in environment by adding or removing web servers and balancing the load between them. It doesn’t have any effect on the CPU power, memory or storage capacity of the web servers powering the app, it only changes the number of instances(web servers).

You can set the minimum and maximum number of instances.

Autoscaling Factors

Autoscaling can be triggered according to a schedule, or by assessing whether the system is running short of resources.

For example, autoscaling could be triggered if

  • CPU utilization grows.

  • Memory occupancy increases.

  • The number of incoming requests to a service appears to be surging or some combination of factors.

Scale-out and scale in options in different tiers:

  • In Basic and Up, only manual autoscaling is supported. Also, no rule based and scheduled based scaling are supported.

  • In Standard and Up, rule based and scheduled based scaling are supported.

Automatic scaling

In Premium and up, Automatic scaling option can be set which automatically handles scaling decisions for your web apps and App Service Plans to avoid cold start issues as it supports minimum 1 prewarmed and always ready instances.

It doesn’t support rule based and scheduled based scaling, the platform manages the scale-out and in based on HTTP traffic.

Monitoring and Logging

We can monitor an app service for its availability, performance, scaling, logs, security, and custom metrics, such as requests, CPU load, and data in/out.

Types of logging supported:

  • Application logging - stored in App Service File System and/or Blobs. Supported by Windows and Linux.

  • Web server logging - stored in App Service File System and/or Blobs. Supported by Windows only.

  • Detailed error messages - stored in App Service File System, supported by Windows only.

  • Failed request tracing - stored in App Service File System, supported by Windows only.

  • Deployment logging - stored in App Service File System and/or Blobs. Supported by Windows and Linux.

Note: File System option is for temporary debugging purpose and it turns off automatically in 12 hours.

It provides the below tools:

  • Azure Monitor: The centralized platform gathers and evaluates metrics and logs from Azure resources, facilitating the monitoring of application performance through the collection of real-time data on CPU usage, memory usage, network traffic, and additional performance metrics.

  • Application Insights: It provides diagnostics that can help in identifying errors, and track performance.

  • Log Analytics: We can monitor the logs generated by the web application using log stream/app service logs.

Deployment Slots

Deployment slots are active environments within an Azure App Service instance. Each slot represents a distinct deployment environment, such as production, staging, or development, operating under the same App Service Plan. These slots enable the deployment and testing of applications without impacting the live production site.

Standard, Premium, and Isolated tiers support option of additional slots.

Default Slots:

  • Production Slot: The default and primary slot where the live application runs.

  • Additional Slots: You can create multiple additional slots (e.g., staging, QA) depending on your App Service Plan's tier.

Benefits of Deployment Slots

  • Zero-Downtime Deployment - Deploy updates to a non-production slot, test them, and then swap them with the production slot, ensuring uninterrupted service for end-users.

  • Testing in a Production-Like Environment - Each slot operates in an isolated environment with its own configuration settings and hostname, making it ideal for thorough testing.

  • Rollback Capabilities - If an update introduces issues, you can swiftly revert to the previous deployment slot, minimizing any disruption.

  • Configuration Isolation - Each slot can have distinct app settings and connection strings, enabling testing with various configurations without affecting the production environment.

  • Traffic Routing - Gradually implement new updates by directing a portion of your users to a staging slot. Azure App Service enables you to route a percentage of your traffic to a non-production slot, which is beneficial for testing new features with a specific group of users. By default, new slots are assigned a routing rule of 0%.

Limitations of Deployment Slots

  • Shared Resources: All slots utilize the same App Service Plan resources, meaning high usage in one slot can affect the performance of others.

  • Slot-Specific Settings: Some settings, such as custom domains and TLS/SSL bindings, are exclusive to the production slot and cannot be configured individually for each slot.

  • Scaling: Slots cannot be scaled independently; scaling adjustments apply to the entire App Service Plan.

Did you find this article valuable?

Support .NET - Sankarshan Ramesh by becoming a sponsor. Any amount is appreciated!