Azure App Service
- Azure App Service is an HTTP-based service for hosting web applications, REST APIs and mobile back ends
- Compatible with both Windows and Linux environments
- Built-in vertical and horizontal auto scaling
- Can deploy and run containerised web apps
- CI/CD with Azure DevOps, GitHub, Bitbucket, FTP or local Git repository
- Swappable deployment slots with their own host names, app content and configurations (Standard App Service Plan tier or above, default is production slot)
- On Linux, can host web apps natively for supported application stacks
- Limitations on Linux:
- No support for Shared pricing tier
- Azure portal only shows features that current work for Linux apps
- When deployed to built-in images, your code and content are allocated a storage volume for web content in Azure Storage with high and variable disk latency + Apps requiring heavy read-only access to content files may benefit from the custom container option, which places files in the container filesystem instead
Plans
- An App Service plan defines a set of compute resources for a web app to run
- Operating system, region, number of VM instances, size of VM instances, pricing tier
- Pricing tiers:
- Shared compute:
- Free, Shared (base tiers)
- Runs an app on the same Azure VM as other App Service apps from other customers
- CPU quotas are allocated to each app running on shared resources which can't be scaled out
- Dedicated compute:
- Basic, Standard, Premium, PremiumV2, PremiumV3
- Run apps on dedicated Azure VMs
- Only apps in the same App Service plan share the compute resources
- Higher tiers increase the availability of VM instances for you to scale out
- Isolated:
- Isolated, IsolatedV2
- Run dedicated Azure VMs on dedicated Azure Virtual Networks
- Provides network isolation on top of compute isolation to your apps
- Provides maximum scale out capabilities
- Shared compute:
How do apps run and scale
- In the base tiers, apps receive CPU minutes on a shared VM instance with no scale out capabilities
- Other tiers scale out as follows:
- App runs on all VM instances configured based on the App Service plan
- If there are multiple apps in the same plan, they share the same VM instances
- If there are multiple deployment slots for an app, all slots run on the same VM instances
- If you enable diagnostic logs, perform backups or run WebJobs, they also use CPU cycles and memory on these VM instances
- Isolation apps into new plans when:
- An app is resource intensive
- Want to scale the app independently from other apps in the same plan
- The app needs resources in a different geographical region
Authentication and Authorisation
- Azure App Service provides built-in authentication and authorisation support
- Sign users in and access data writing minimal to no code, doesn't require any particular language or security expertise
- Can integrate with multiple login providers, such as Microsoft Entra ID, Facebook, Google and X (Twitter)
- Contains a built-in repository for tokens associated with users, APIs or native mobile apps
- Can enable logging and tracing for authentication and authorisation
How does it work
- The authentication and authorisation modules handle incoming HTTP requests before your application code does
- Authenticates users and clients with the specified identity providers
- Validates, stores and refreshes OAuth tokens issued by identity providers
- Manages authenticated session
- Injects identity information into HTTP request headers
Authentication flow
- Without provider SDK:
- Sign user in: Redirects client to /.auth/login/<provider>
- Post-authentication: Provider redirects client to /.auth/login/<provider>/callback
- Establish authenticated session: App Service adds authenticated cookie to response
- Serve authenticated content: Client includes authentication cookie in subsequent requests (automatically handled by browser)
- With provider SDK:
- Sign user in: Client code signs user in directly with provider's SDK and receives an authentication token
- Post-authentication: Client code posts token from provider to /.auth/login/<provider> for validation
- Establish authenticated session: App Service returns its own authentication token to client code
- Serve authenticated content: Client code presents authentication token in X-ZUMO-AUTH header (automatically handled by Mobile App client SDKs)
Authorisation behaviour
- Allow unauthenticated requests: Can defer authorisation of unauthenticated traffic to your application code
- Require authentication: Rejects any unauthenticated traffic. Can redirect to a configured identity provider or for anonymous requests, can return a HTTP 401 or 403 error
Networking features
- There are two main deployment types:
- Multi-tenant (Free and Shared SKU plans)
- Single-tenant (Basic and higher plans)
- Azure App Service is a distributed system with the follolwing roles: Front ends: Handle incoming HTTP/S requests Workers: Host the customer workload
- If you're running your app in a multi-tenant environment you can't connect the App Service directly to your network. Instead you need to use features:
- Inbound features:
- App-assigned address
- Access restrictions
- Service endpoints
- Private endpoints
- Outbound features:
- Hybrid connections
- Gateway-required virtual network integration
- Virtual network integration
- Inbound features:
- You can view the outbound IP addresses (and possible outbound IP addresses) of the worker VM families hosting your apps with the following Azure CLI commands:
az webapp show \ --resource-group <group_name> \ --name <app_name> \ --query outboundIpAddresses \ --output tsv az webapp show \ --resource-group <group_name> \ --name <app_name> \ --query possibleOutboundIpAddresses \ --output tsv
Configure application settings
- App settings are variables passed as environment variables to the application code
- For Linux apps and containers, settings are passed using the --env flag
- Passwords / production secrets can be stored safely as app settings are always encrypted-at-rest
- Adding and editting settings can be performed through a GUI or JSON format via Azure Portal
- Settings can also be supplied externally as arguments via Cloud Shell
- Azure CLI:
az webapp config appsettings set --resource-group <group-name> --name <app-name> --settings key1=value1 key2=value2
- Azure PowerShell:
Set-AzWebApp -ResourceGroupName <group-name> -Name <app-name> -AppSettings @{"DB_HOST"="myownserver.mysql.database.azure.com"}
- Environment variable settings can be verified through the URL format: https://<app-name>.scm.azurewebsites.net/Env
Configure general settings
- Common settings can be configured in the section Configuration > General settings
- Some settings require higher pricing tiers
- List of currently available settings:
- Stack settings: Software stack to run the app (includes language, SDK versions, optional start-up for Linux / custom containers)
- Platform settings: Settings for the hosting platform
- Platform bitness: 32-bit or 64-bit (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: (ex. ASP.NET Signal or socket.io)
- Always On: Keeps app loaded even if no traffic, a load balancer sends a GET request to the application root every 5 minutes to prevent inactivity. By default, it's off and the app is unloaded after 20 minutes without any incoming requests
- ARR affinity: Ensure client is routed to same instance within the session for multi-instance deployments. Disable this option for stateless applications
- Debugging: Enables remote debugging for ASP.NET, ASP.NET Core or Node.js apps. Turns off automatically after 48 hours
- Incoming client certificates: TLS mutual authentication will require client certificates
Configure path mappings
- Handler mappings, virtual application and directory mappings can be configured in hte section Configuration > Path mappings
- Custom handlers for uncontainerised Windows apps:
- Extension: File extension to target
- Script processor: Absolute path of script processor which processes files matching the extension. D:\home\site\wwwroot refers to your app's root directory
- Arguments: Optional command line arguments for the script processor
- Custom storage for Linux apps, Windows and Linux custom containers:
- Name: Display name
- Configuration options: Basic (use if account does not use service endpoints, private endpoints or Azure Key Vault). Otherwise, use Advanced
- Storage accounts: Storage account with the container you want
- Storage type: Azure Blobs / Azure Files. Window container apps can only use the latter, the former only supports read-only access
- Storage container: The container you want (for basic config.)
- Share name: File share name (for advanced config.)
- Access key: Access key (for advanced config.)
- Mount path: Absolute path in your container to mount the custom storage
- Deployment slot setting: Storage mount settings also apply to deployment slots if enabled
Enable diagnostic logging
Type | Platform | Location | Description |
---|---|---|---|
Application logging | Windows, Linux | App Service file system and/or Azure Storage blobs | Logs messages generated by your application code. The messages are generated by the web framework you choose, or from your application code directly using the standard logging pattern of your language. Each message is assigned one of the following categories: Critical, Error, Warning, Info, Debug, and Trace. |
Web server logging | Windows | App Service file system or Azure Storage blobs | Raw HTTP request data in the W3C extended log file format. Each log message includes data like the HTTP method, resource URI, client IP, client port, user agent, response code, and so on. |
Detailed error messages | Windows | App Service file system | Copies of the .html error pages that would have been sent to the client browser. For security reasons, detailed error pages shouldn't be sent to clients in production, but App Service can save the error page each time an application error occurs that has HTTP code 400 or greater. |
Failed request tracing | Windows | App Service file system | Detailed tracing information on failed requests, including a trace of the IIS components used to process the request and the time taken in each component. One folder is generated for each failed request, which contains the XML log file, and the XSL stylesheet to view the log file with. |
Deployment logging | Windows, Linux | App Service file system | Helps determine why a deployment failed. Deployment logging happens automatically and there are no configurable settings for deployment logging. |
- To enable application logging for Windows:
- Navigate to your app and select App Service logs
- Enable either Application Logging (Filesystem) or Application Logging (Blob) or both
- Filesystem is for temporary debugging, it automatically turns off after 12 hours
- Blob is for long-term logging and it writes logs to a blob storage container
- The Level of details included in the log (Disabled, Error, Warning, Information, Verbose)
- To enable application logging for Linux / containers:
- In App Service logs, set Application logging to File System
- In Quota (MB), specify the disk quota for application logs. Set the log retention period in Retention Period (Days)
- Logging facilties can also be used to send log messages from the application code to the application logs
- ASP.NET applications can use System.Diagnostics.Trace. By default, ASP.NET Core uses Microsoft.Extensions.Logging.AzureAppServices logging provider
- Python applications can use the OpenCensus package
- Streaming logs:
- Information written to .txt, .log or .htm files within d:/home/logfiles is streamed by App Service
- Azure portal: Select Log Stream after navigating to your app via Azure Portal
- Azure CLI:
az webapp log tail --name appname --resource-group myResourceGroup
- Local console: Install Azure CLI, sign in then run the command above
- To access log files stored in the App Service file system, the simplest way is to download the ZIP file at the following URLs
- Linux / container apps: https://<app-name>.scm.azurewebsites.net/api/logs/docker/zip
- Windows apps: https://<app-name>.scm.azurewebsites.net/api/dump
Configure security certificates
Option | Description |
---|---|
Create a free App Service managed certificate | A private certificate that's free of charge and easy to use if you just need to secure your custom domain in App Service. |
Purchase an App Service certificate | A private certificate that's managed by Azure. It combines the simplicity of automated certificate management and the flexibility of renewal and export options. |
Import a certificate from Key Vault | Useful if you use Azure Key Vault to manage your certificates. |
Upload a private certificate | If you already have a private certificate from a third-party provider, you can upload it. |
Upload a public certificate | Public certificates aren't used to secure custom domains, but you can load them into your code if you need them to access remote resources. |
- The free App Service managed certificate and App Service certificate already satisfy requirements of the App Service
- To use a private certificate, it must meet the following requirements:
- Exported as a password-protected PFX file, encrypted using triple DES
- Contains a private key at least 2048 bits long
- Contains all intermediate certificates and the root certificate in the certificate chain
- To secure a custom domain in a TLS binding, the other certificate requirements are:
- Contains an Extended Key Usage for server authentication (OID = 1.3.6.1.5.5.7.3.1)
- Signed by a trusted certificate authority
- To use a private certificate, it must meet the following requirements:
- To create custom TLS/SSL bindings or enable client certificates for your app, your plan must be in one of the following tiers: Basic, Standard, Premium or Isolated
- The TLS/SSL server certificate is fully managed and renewed automatically every 6 months 45 days before expiration
- The user only needs to create the certificate and bind it to a custom domain
- Free certificates come with the following limitations:
- Doesn't support wildcard certificates
- Doesn't support usage as a client certificate by using certificate thumbprint (planned to be deprecated and removed)
- Doesn't support private DNS
- Not exportable
- Not supported in an App Service Environment (ASE)
- Only supports alphanumeric characters, dashes and periods
- Only custom domains of length up to 64 characters are supported
- If you have a working App Service certificate, you can import it into the App Service and manage it (renew, rekey, export)
- Azure manages the following tasks if you purchase a certificate from them:
- Takes care of the purchase process from the certificate provider
- Performs domain verification of the certificate
- Maintains the certificate in Azure Key Vault
- Manages certificate renewal
- Synchronises the certificate automatically with the imported copies in App Service apps
- Azure manages the following tasks if you purchase a certificate from them:
- Currently, App Service Certificates are not supported in Azure National Clouds
Scale out options
-
Two options for automatic web scaling:
- Azure autoscale: Scaling decisions are based on user-defined rules
- Azure App Service automatic scaling: Scaling decisions are based on the parameters you select
- Scenarios to use:
- Don't want to set up rules based on resource metrics
- Want web apps within an App Service Plan to scale differently and independently
- Want to set a maximum number of instances to prevent overwhelming the backend if it uses slow scaling legacy systems or databases
- Scenarios to use:
-
Scales in and out, adding and removing web servers to balance the load
-
Rules specify threshold for a metric which triggers and autoscale event
-
The elasticity provides reliability and fault tolerance
Identify autoscale factors
- Autoscaling in App Service Plan allows you to set an instance limit
- Limit increases with higher pricing tiers (not all plans support this feature)
- Azure provides two options for autoscaling conditions:
- Scale based on metric (ex. length of disk queue, number of HTTP requests awaiting processing)
- Scale to a specific instance count based off schedule (ex. arrange to scale out at a certain time, then scales back in at the end of the period)
- Metrics for autoscale rules:
- CPU Percentage: Indicates CPU usage across all instances
- Memory Percentage: Captures memory occupancy of the application across all instances
- Disk Queue Length: Measure of outstanding I/O requests across all instances
- HTTP Queue Length: Number of client requests waiting for processing by the web app
- Data In: Number of bytes received across all instances
- Data Out: Number of bytes sent by all instances
- Autoscale rules should have paired conditions
- Scaling-out when the metric exceeds the upper threshold
- Scaling-in when the metric drops below the lower threshold
Enable autoscale in App Service
- In the Azure Portal, go to your App Service plan and select Settings > Scale out (App Service plan)
- By default, scaling is manual
- Custom autoscale allows you to define condition groups for managing scale settings
- Within the Run history section, you can also monitor autoscaling activities
- In Activity log, you can configure it so notifications are alerted via email, SMS or webhooks
- Issues with autoscale operations
- Successful autoscale operations
- Failed autoscale operations
- Metrics aren't available to make a scale decision
- Metrics are available (recovery) to make a scale decision
Autoscale best practices
- Ensure maximum and minimum values are different with adequate margin between them
- Choose the appropriate statistic for your diagnostics metric
- Choose the thresholds carefully for all metric types
- Considerations for scaling when multiple rules are configured in a profile
- Always select a safe default instance count
- Configure autoscale notifications
Staging environments
- Standard, Premium and Isolated plans support deployment to a specified deployment slot instead of the default production slot
- Each tier supports a different number of deployment slots
- No extra charge for using deployment slots
- Ensure when scaling to a different tier, it supports at least the number of slots your app is currently using
- Deployment slots are live apps with their own host names
- Benefits of deploying an app to a non-production slot:
- Validate app changes in a staging deployment slot before swapping it with a production slot
- Deploying to a slot first before swapping to production ensures all instances of the slot are warmed up first, eliminating downtime
- After a swap, the previous production app is in the staging slot. If the current changes in the production slot aren't expected, you can swap back to the last "checkpoint"
Slot swapping
- Process of swapping two slots (staging to production):
- Apply slot-specific app settings, connection strings, continuous deployment settings and App Service authentication settings from the target slot to all instances of the source slot
- Wait for all instances in the source slot to restart, failure to one instance will revert all changes
- Trigger local cache initialisation (if enabled) by making an HTTP request to every instance of the source slot, waiting for each instance to return an HTTP response
- Trigger Application Initiation by making an HTTP request to every instance of the source slot, instances returning a response are considered warmed up
- If all instances are warmed up, swap the slots by switching the routing rules for both slots. The target slot should have the app that's previously warmed up in the source slot
- Now the source slot has the pre-swap app previously in the target slot, perform the same operation by applying all settings and restarting the instances
- At any point during the swap operation, target slot is online and functioning while the source slot is being prepared and warmed up
- The following table shows settings that change when you swap slots:
- Some configurations follow the content across a swap (not slot specific), whereas others stay in the same slot after a swap (slot specific)
- Features marked with an asterisk (*) are planned to be unswapped
Settings that are swapped | Settings that aren't swapped |
---|---|
General settings, such as framework version, 32/64-bit, web sockets | Publishing endpoints |
App settings (can be configured to stick to a slot) | Custom domain names |
Connection strings (can be configured to stick to a slot) | Non-public certificates and TLS/SSL settings |
Handler mappings | Scale settings |
Public certificates | WebJobs schedulers |
WebJobs content | IP restrictions |
Hybrid connections * | Always On |
Azure Content Delivery Network * | Diagnostic log settings |
Service endpoints * | Cross-origin resource sharing (CORS) |
Path mappings | Virtual network integration |
Managed identities | |
Settings that end with the suffix _EXTENSION_VERSION |
Swap deployment slots
- Manually swapping deployment slots:
- Go to Deployment slots > Swap and select the Source and Target slots
- Before swapping, validate the app runs with swapped settings with preview
- Enable Perform swap with preview
- When a swap is started, you can preview the app at https://<app_name>-<source-slot-name>.azurewebsites.net and puts the swap in a pending state
- If everything looks good, complete the swap
- Auto swap streamlines Azure DevOps Services to continuously deploy your app with zero cold starts and downtime
- When enabling it from a slot into production, it allows the new app to swap into production after being warmed up in the source slot whenever code changes are pushed into that slot
- Go to Configuration > General settings in your app's resource page to configure auto swap
Specify custom warm-up
- Some apps might require custom warm-up actions before the swap
- In web.config, the applicationInitialization element lets you specify custom initialisation actions
<system.webServer> <applicationInitialization> <add initializationPage="/" hostName="[app hostname]" /> <add initializationPage="/Home/About" hostName="[app hostname]" /> </applicationInitialization> </system.webServer>
- Customise warm-up behaviour:
- WEBSITE_SWAP_WARMUP_PING_PATH: Path to ping your warmup site, default value is /
- WEBSITE_SWAP_WARMUP_PING_STATUSES: A comma-separated list of valid HTTP response codes for the warm-up operation
- WEBSITE_WARMUP_PATH: A relative path on the site that should be pinged whenever the site restarts (not only during slot swaps)
- Roll back and monitoring swaps
- If any error occurs in the target slot after a slot swap, it restores the slots to their pre-swap states by swapping the same two slots immediately
- You can also view more information in the activity log if an operation takes too long
Route traffic in App Service
- All client requests to the app's production URL (http://<app_name>.azurewebsites.net) are routed to the production slot by default
- To route production traffic automatically:
- Go to app's resource page and select Deployment slots
- In the Traffic % section, specify a percentage of total traffic to route
- When a client is routed to a slot, it's "pinned" to that slot for the remainder of the session
- The "pinned" slot can be viewed in the x-ms-routing-name cookie in the HTTP headers
- To route production traffic manually:
- Use the x-ms-routing-name query parameter
- Allow users to opt out of your beta app
<a href="<webappname>.azurewebsites.net/?x-ms-routing-name=self">Go back to production app</a>
- Allow users to opt into your beta app by setting the same query parameter to the name of the non-production slot
<webappname>.azurewebsites.net/?x-ms-routing-name=staging