Set up staging environments in Azure App Service

Note

Starting June 1, 2024, all newly created App Service apps will have the option to generate a unique default hostname using the naming convention <app-name>-<random-hash>.<region>.azurewebsites.net. Existing app names will remain unchanged.

Example: myapp-ds27dh7271aah175.westus-01.azurewebsites.net

For further details, refer to Unique Default Hostname for App Service Resource.

When you deploy your web app, web app on Linux, mobile back end, or API app to Azure App Service, you can use a separate deployment slot instead of the default production slot when you're running in the Standard, Premium, or Isolated App Service plan tier. Deployment slots are live apps with their own host names. App content and configurations elements can be swapped between two deployment slots, including the production slot.

Deploying your application to a nonproduction slot has the following benefits:

  • You can validate app changes in a staging deployment slot before swapping it with the production slot.
  • Deploying an app to a slot first and swapping it into production makes sure that all instances of the slot are warmed up before being swapped into production. This eliminates downtime when you deploy your app. The traffic redirection is seamless, and no requests are dropped because of swap operations. You can automate this entire workflow by configuring auto swap when pre-swap validation isn't needed.
  • After a swap, the slot with previously staged app now has the previous production app. If the changes swapped into the production slot aren't as you expect, you can perform the same swap immediately to get your "last known good site" back.

Each App Service plan tier supports a different number of deployment slots. There's no extra charge for using deployment slots. To find out the number of slots your app's tier supports, see App Service limits.

To scale your app to a different tier, make sure that the target tier supports the number of slots your app already uses. For example, if your app has more than five slots, you can't scale it down to the Standard tier, because the Standard tier supports only five deployment slots.

This video shows you how to set up staging environments in Azure App Service.

The steps in the video are also described in the following sections.

Prerequisites

For information on the permissions you need to perform the slot operation you want, see Resource provider operations (search for slot, for example).

Add a slot

The app must be running in the Standard, Premium, or Isolated tier in order for you to enable multiple deployment slots.

  1. In the Azure portal, navigate to your app's management page.

  2. In the left pane, select Deployment slots > Add Slot.

    Note

    If the app isn't already in the Standard, Premium, or Isolated tier, select Upgrade and go to the Scale tab of your app before continuing.

  3. In the Add a slot dialog box, give the slot a name, and select whether to clone an app configuration from another deployment slot. Select Add to continue.

    A screenshot that shows how to configure a new deployment slot called 'staging' in the portal.

    You can clone a configuration from any existing slot. Settings that can be cloned include app settings, connection strings, language framework versions, web sockets, HTTP version, and platform bitness.

    Note

    Currently, a private endpoint isn't cloned across slots.

  4. After the slot is added, select Close to close the dialog box. The new slot is now shown on the Deployment slots page. By default, Traffic % is set to 0 for the new slot, with all customer traffic routed to the production slot.

  5. Select the new deployment slot to open that slot's resource page.

    A screenshot that shows how to open deployment slot's management page in the portal.

    The staging slot has a management page just like any other App Service app. You can change the slot's configuration. To remind you that you're viewing the deployment slot, the app name is shown as <app-name>/<slot-name>, and the app type is App Service (Slot). You can also see the slot as a separate app in your resource group, with the same designations.

  6. Select the app URL on the slot's resource page. The deployment slot has its own host name and is also a live app. To limit public access to the deployment slot, see Azure App Service IP restrictions.

The new deployment slot has no content, even if you clone the settings from a different slot. For example, you can publish to this slot with Git. You can deploy to the slot from a different repository branch or a different repository. Get publish profile from Azure App Service can provide required information to deploy to the slot. The profile can be imported by Visual Studio to deploy contents to the slot.

The slot's URL has the format http://sitename-slotname.azurewebsites.net. To keep the URL length within necessary DNS limits, the site name will be truncated at 40 characters, and the combined site name and slot name must be fewer than 59 characters.

What happens during a swap

Swap operation steps

When you swap two slots (usually from a staging slot as the source into the production slot as the target), App Service does the following to ensure that the target slot doesn't experience downtime:

  1. Apply the following settings from the target slot (for example, the production slot) to all instances of the source slot:

    Any of these cases trigger all instances in the source slot to restart. During swap with preview, this marks the end of the first phase. The swap operation is paused, and you can validate that the source slot works correctly with the target slot's settings.

  2. Wait for every instance in the source slot to complete its restart. If any instance fails to restart, the swap operation reverts all changes to the source slot and stops the operation.

  3. If local cache is enabled, trigger local cache initialization by making an HTTP request to the application root ("/") on each instance of the source slot. Wait until each instance returns any HTTP response. Local cache initialization causes another restart on each instance.

  4. If auto swap is enabled with custom warm-up, trigger Application Initiation by making an HTTP request to the application root ("/") on each instance of the source slot.

    If applicationInitialization isn't specified, trigger an HTTP request to the application root of the source slot on each instance.

    If an instance returns any HTTP response, it's considered to be warmed up.

  5. If all instances on the source slot are warmed up successfully, swap the two slots by switching the routing rules for the two slots. After this step, the target slot (for example, the production slot) has the app that's previously warmed up in the source slot.

  6. Now that 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 of the swap operation, all work of initializing the swapped apps happens on the source slot. The target slot remains online while the source slot is being prepared and warmed up, regardless of where the swap succeeds or fails. To swap a staging slot with the production slot, make sure that the production slot is always the target slot. This way, the swap operation doesn't affect your production app.

Note

The instances in your former production instances (those that will be swapped into staging after this swap operation) will be recycled quickly in the last step of the swap process. In case you have any long running operations in your application, they will be abandoned, when the workers recycle. This also applies to function apps. Therefore your application code should be written in a fault tolerant way.

Which settings are swapped?

When you clone configuration from another deployment slot, the cloned configuration is editable. Some configuration elements follow the content across a swap (not slot specific), whereas other configuration elements stay in the same slot after a swap (slot specific). The following lists show the settings that change when you swap slots.

Settings that are swapped:

  • General settings, such as framework version, 32/64-bit, web sockets
  • App settings (can be configured to stick to a slot)
  • Connection strings (can be configured to stick to a slot)
  • Handler mappings
  • Public certificates
  • WebJobs content
  • Hybrid connections *
  • Service endpoints *
  • Azure Content Delivery Network *
  • Path mappings

Features marked with an asterisk (*) are planned to be unswapped.

Settings that aren't swapped:

  • Publishing endpoints
  • Custom domain names
  • Non-public certificates and TLS/SSL settings
  • Scale settings
  • WebJobs schedulers
  • IP restrictions
  • Always On
  • Diagnostic settings
  • Cross-origin resource sharing (CORS)
  • Virtual network integration
  • Managed identities and related settings
  • Settings that end with the suffix _EXTENSION_VERSION
  • Settings that created by Service Connector

Note

To make aforementioned settings swappable, add the app setting WEBSITE_OVERRIDE_PRESERVE_DEFAULT_STICKY_SLOT_SETTINGS in every slot of the app and set its value to 0 or false. These settings are either all swappable or not at all. You can't make just some settings swappable and not the others. Managed identities are never swapped and are not affected by this override app setting.

Certain app settings that apply to unswapped settings are also not swapped. For example, since diagnostic settings are not swapped, related app settings like WEBSITE_HTTPLOGGING_RETENTION_DAYS and DIAGNOSTICS_AZUREBLOBRETENTIONDAYS are also not swapped, even if they don't show up as slot settings.

To configure an app setting or connection string to stick to a specific slot (not swapped), go to the Configuration page for that slot. Add or edit a setting, and then select deployment slot setting. Selecting this check box tells App Service that the setting isn't swappable.

A screenshot that shows how to configure an app setting as a slot setting in the Azure portal.

Swap two slots

You can swap deployment slots on your app's Deployment slots page and the Overview page. For technical details on the slot swap, see What happens during swap.

Important

Before you swap an app from a deployment slot into production, make sure that production is your target slot and that all settings in the source slot are configured exactly as you want to have them in production.

To swap deployment slots:

  1. Go to your app's Deployment slots page and select Swap.

    A screenshot that shows how to initiate a swap operation in the portal.

    The Swap dialog box shows settings in the selected source and target slots that will be changed.

  2. Select the desired Source and Target slots. Usually, the target is the production slot. Also, select the Source Changes and Target Changes tabs and verify that the configuration changes are expected. When you're finished, you can swap the slots immediately by selecting Swap.

    A screenshot that shows how to configure and complete a swap in the portal.

    To see how your target slot would run with the new settings before the swap actually happens, don't select Swap, but follow the instructions in Swap with preview.

  3. When you're finished, close the dialog box by selecting Close.

If you have any problems, see Troubleshoot swaps.

Swap with preview (multi-phase swap)

Before you swap into production as the target slot, validate that the app runs with the swapped settings. The source slot is also warmed up before the swap completion, which is desirable for mission-critical applications.

When you perform a swap with preview, App Service performs the same swap operation but pauses after the first step. You can then verify the result on the staging slot before completing the swap.

If you cancel the swap, App Service reapplies configuration elements to the source slot.

Note

Swap with preview can't be used when one of the slots has site authentication enabled.

To swap with preview:

  1. Follow the steps in Swap deployment slots but select Perform swap with preview.

    A screenshot that shows how to configure a swap with preview in the portal.

    The dialog box shows you how the configuration in the source slot changes in phase 1, and how the source and target slot change in phase 2.

  2. When you're ready to start the swap, select Start Swap.

    When phase 1 finishes, you're notified in the dialog box. Preview the swap in the source slot by going to https://<app_name>-<source-slot-name>.azurewebsites.net.

  3. When you're ready to complete the pending swap, select Complete Swap in Swap action and select Complete Swap.

    To cancel a pending swap, select Cancel Swap instead, and then select Cancel Swap at the bottom.

  4. When you're finished, close the dialog box by selecting Close.

If you have any problems, see Troubleshoot swaps.

Roll back a swap

If any errors occur in the target slot (for example, the production slot) after a slot swap, restore the slots to their pre-swap states by swapping the same two slots immediately.

Configure auto swap

Note

Auto swap isn't supported in web apps on Linux and Web App for Containers.

Auto swap streamlines Azure DevOps scenarios where you want to deploy your app continuously with zero cold starts and zero downtime for customers of the app. When auto swap is enabled from a slot into production, every time you push your code changes to that slot, App Service automatically swaps the app into production after it's warmed up in the source slot.

Note

Before you configure auto swap for the production slot, consider testing auto swap on a nonproduction target slot.

To configure auto swap:

  1. Go to your app's resource page. Select Deployment slots > <desired source slot> > Configuration > General settings.

  2. For Auto swap enabled, select On. Then select the desired target slot for Auto swap deployment slot, and select Save on the command bar.

    A screenshot that shows how to configure auto swap into the production slot in the portal.

  3. Execute a code push to the source slot. Auto swap happens after a short time, and the update is reflected at your target slot's URL.

If you have any problems, see Troubleshoot swaps.

Specify custom warm-up

Some apps might require custom warm-up actions before the swap. The applicationInitialization configuration element in web.config lets you specify custom initialization actions. The swap operation waits for this custom warm-up to finish before swapping with the target slot. Here's a sample web.config fragment.

<system.webServer>
    <applicationInitialization>
        <add initializationPage="/" hostName="[app hostname]" />
        <add initializationPage="/Home/About" hostName="[app hostname]" />
    </applicationInitialization>
</system.webServer>

For more information on customizing the applicationInitialization element, see Most common deployment slot swap failures and how to fix them.

You can also customize the warm-up behavior with one or both of the following app settings:

  • WEBSITE_SWAP_WARMUP_PING_PATH: The path to ping over HTTP to warm up your site. Add this app setting by specifying a custom path that begins with a slash as the value. An example is /statuscheck. The default value is /.
  • WEBSITE_SWAP_WARMUP_PING_STATUSES: Valid HTTP response codes for the warm-up operation. Add this app setting with a comma-separated list of HTTP codes. An example is 200,202 . If the returned status code isn't in the list, the warmup and swap operations are stopped. By default, all response codes are valid.
  • WEBSITE_WARMUP_PATH: A relative path on the site that should be pinged whenever the site restarts (not only during slot swaps). Example values include /statuscheck or the root path, /.

Note

The <applicationInitialization> configuration element is part of each app start-up, whereas the two warm-up behavior app settings apply only to slot swaps.

If you have any problems, see Troubleshoot swaps.

Monitor a swap

If the swap operation takes a long time to complete, you can get information on the swap operation in the activity log.

On your app's resource page in the portal, in the left pane, select Activity log.

A swap operation appears in the log query as Swap Web App Slots. You can expand it and select one of the suboperations or errors to see the details.

Route production traffic automatically

By default, all client requests to the app's production URL (http://<app_name>.azurewebsites.net) are routed to the production slot. You can route a portion of the traffic to another slot. This feature is useful if you need user feedback for a new update, but you're not ready to release it to production.

To route production traffic automatically:

  1. Go to your app's resource page and select Deployment slots.

  2. In the Traffic % column of the slot you want to route to, specify a percentage (between 0 and 100) to represent the amount of total traffic you want to route. Select Save.

    A screenshot that shows how to route a percentage of request traffic to a deployment slot, in the portal.

After the setting is saved, the specified percentage of clients is randomly routed to the nonproduction slot.

After a client is automatically routed to a specific slot, it's "pinned" to that slot for one hour or until the cookies are deleted. On the client browser, you can see which slot your session is pinned to by looking at the x-ms-routing-name cookie in your HTTP headers. A request that's routed to the "staging" slot has the cookie x-ms-routing-name=staging. A request that's routed to the production slot has the cookie x-ms-routing-name=self.

Route production traffic manually

In addition to automatic traffic routing, App Service can route requests to a specific slot. This is useful when you want your users to be able to opt in to or opt out of your beta app. To route production traffic manually, you use the x-ms-routing-name query parameter.

To let users opt out of your beta app, for example, you can put this link on your webpage:

<a href="<webappname>.azurewebsites.net/?x-ms-routing-name=self">Go back to production app</a>

The string x-ms-routing-name=self specifies the production slot. After the client browser accesses the link, it's redirected to the production slot. Every subsequent request has the x-ms-routing-name=self cookie that pins the session to the production slot.

To let users opt in to your beta app, set the same query parameter to the name of the nonproduction slot. Here's an example:

<webappname>.azurewebsites.net/?x-ms-routing-name=staging

By default, new slots are given a routing rule of 0%, shown in grey. When you explicitly set this value to 0% (shown in black text), your users can access the staging slot manually by using the x-ms-routing-name query parameter. But they won't be routed to the slot automatically because the routing percentage is set to 0. This is an advanced scenario where you can "hide" your staging slot from the public while allowing internal teams to test changes on the slot.

Delete a slot

Search for and select your app. Select Deployment slots > <slot to delete> > Overview. The app type is shown as App Service (Slot) to remind you that you're viewing a deployment slot. Before deleting a slot, make sure to stop the slot and set the traffic in the slot to zero. Select Delete on the command bar.

A screenshot that shows how to delete a deployment slot in the portal.

Automate with Resource Manager templates

Azure Resource Manager templates are declarative JSON files used to automate the deployment and configuration of Azure resources. To swap slots by using Resource Manager templates, you set two properties on the Microsoft.Web/sites/slots and Microsoft.Web/sites resources:

  • buildVersion: this is a string property that represents the current version of the app deployed in the slot. For example: "v1", "1.0.0.1", or "2019-09-20T11:53:25.2887393-07:00".
  • targetBuildVersion: this is a string property that specifies what buildVersion the slot should have. If the targetBuildVersion doesn't equal the current buildVersion, it triggers the swap operation by finding the slot with the specified buildVersion.

Example Resource Manager template

The following Resource Manager template swap two slots by updating the buildVersion of the staging slot and setting the targetBuildVersion on the production slot. It assumes you've created a slot called staging.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "my_site_name": {
            "defaultValue": "SwapAPIDemo",
            "type": "String"
        },
        "sites_buildVersion": {
            "defaultValue": "v1",
            "type": "String"
        }
    },
    "resources": [
        {
            "type": "Microsoft.Web/sites/slots",
            "apiVersion": "2018-02-01",
            "name": "[concat(parameters('my_site_name'), '/staging')]",
            "location": "East US",
            "kind": "app",
            "properties": {
                "buildVersion": "[parameters('sites_buildVersion')]"
            }
        },
        {
            "type": "Microsoft.Web/sites",
            "apiVersion": "2018-02-01",
            "name": "[parameters('my_site_name')]",
            "location": "East US",
            "kind": "app",
            "dependsOn": [
                "[resourceId('Microsoft.Web/sites/slots', parameters('my_site_name'), 'staging')]"
            ],
            "properties": {
                "targetBuildVersion": "[parameters('sites_buildVersion')]"
            }
        }        
    ]
}

This Resource Manager template is idempotent, meaning that it can be executed repeatedly and produce the same state of the slots. Without any change to the template, subsequent runs of the same template don't trigger any slot swap because the slots are already in the desired state.

Troubleshoot swaps

If any error occurs during a slot swap, it's logged in D:\home\LogFiles\eventlog.xml. It's also logged in the application-specific error log.

Here are some common swap errors:

  • An HTTP request to the application root is timed. The swap operation waits for 90 seconds for each HTTP request, and retries up to five times. If all retries are timed out, the swap operation is stopped.

  • Local cache initialization might fail when the app content exceeds the local disk quota specified for the local cache. For more information, see Local cache overview.

  • During a site update operation, the following error may occur "The slot cannot be changed because its configuration settings have been prepared for swap". This can occur if either swap with preview (multi-phase swap) phase 1 has been completed but phase 2 has not yet been performed, or a swap has failed. There are two ways to resolve this issue:

    1. Cancel the swap operation which will reset the site back to the old state
    2. Complete the swap operation which will update site to the desired new state

    Refer to swap with preview (multi-phase swap) to learn how to cancel or complete the swap operation.

  • During custom warm-up, the HTTP requests are made internally (without going through the external URL). They can fail with certain URL rewrite rules in Web.config. For example, rules for redirecting domain names or enforcing HTTPS can prevent warm-up requests from reaching the app code. To work around this issue, modify your rewrite rules by adding the following two conditions:

    <conditions>
      <add input="{WARMUP_REQUEST}" pattern="1" negate="true" />
      <add input="{REMOTE_ADDR}" pattern="^100?\." negate="true" />
      ...
    </conditions>
    
  • Without a custom warm-up, the URL rewrite rules can still block HTTP requests. To work around this issue, modify your rewrite rules by adding the following condition:

    <conditions>
      <add input="{REMOTE_ADDR}" pattern="^100?\." negate="true" />
      ...
    </conditions>
    
  • After slot swaps, the app may experience unexpected restarts. This is because after a swap, the hostname binding configuration goes out of sync, which by itself doesn't cause restarts. However, certain underlying storage events (such as storage volume failovers) may detect these discrepancies and force all worker processes to restart. To minimize these types of restarts, set the WEBSITE_ADD_SITENAME_BINDINGS_IN_APPHOST_CONFIG=1 app setting on all slots. However, this app setting does not work with Windows Communication Foundation (WCF) apps.

Next steps

Block access to nonproduction slots