Skip to main content

Host Vox on Azure App Service

This guide takes a Vox application to production on Azure App Service: create the app, keep it running, let it stop gracefully, scale it out and release new versions with deployment slots. It covers what's specific to App Service and links to the other hosting pages for the rest.

Before you start

You need a Vox application that runs locally with app.RunVoxAsync(args), see add Vox to your application, and an Azure subscription where you can create an App Service plan, a database and a key vault.

What you'll set up​

The guide sets up:

  • An App Service app on a Premium plan, eg with three instances that each serve the API and the admin UI and run Vox's background work. A busier installation splits the API and the processing into two apps, see host roles.
  • A staging deployment slot for blue/green releases.
  • The Vox database on Azure SQL Database or Azure Database for PostgreSQL, see databases.
  • Azure Cache for Redis, if the application has transient entities such as carts, see Redis for transient entities.
  • A key vault for the connection strings and keys.

Create the app​

Create the app with the .NET runtime stack that the application targets, and deploy it as code, eg with ZIP deploy from the pipeline. App Service runs it on Linux or Windows:

  • Linux needs a startup command so the application can stop gracefully, see let the app stop gracefully.
  • Windows runs the application behind IIS and the ASP.NET Core Module, and needs no startup command.

A custom container works too. Its entrypoint must start the .NET process directly, eg ENTRYPOINT ["dotnet", "MyShop.Api.dll"], rather than through a shell script, so the stop signal reaches it.

Keep the app running​

Turn on Always On. Without it, App Service unloads an app that hasn't had a request for 20 minutes, and Vox's background work stops with it: a campaign scheduled to publish at midnight isn't published, and a nightly feed isn't built, until someone opens the shop or the admin. Turn it on in Settings > Configuration > General settings, or with:

az webapp config set --resource-group shop-rg --name shop-api --always-on true

Always On isn't swapped with a slot, so set it on the staging slot too.

Give App Service a health check path. App Service pings it every minute, takes an instance out of the load balancer after 10 failed pings in a row (WEBSITE_HEALTHCHECK_MAXPINGFAILURES, 2 to 10), and replaces an instance that stays unhealthy for an hour. Point it at an endpoint that answers as long as the process runs, and does nothing else:

Program.cs
app.MapGet("/health/live", () => "OK").AllowAnonymous();

Set the path in Monitoring > Health check. The endpoint must answer with a 2xx status without a redirect, so keep it out of an HTTPS redirect. App Service's ping carries no credentials. AllowAnonymous() keeps the endpoint reachable when the application requires a signed-in user by default, eg with a fallback authorization policy. App Service only takes an instance out of the load balancer when the app runs on at least two instances.

A Vox host serves requests as soon as it starts, also a new release in standby, so it needs no separate readiness check.

Don't add checks of the database, Redis, the search index or other shared services to the endpoint, although Microsoft's general advice is to check critical components:

  • A shared service fails on every instance at once. App Service then keeps all instances in the load balancer, but replaces them, one an hour. A replacement doesn't bring the database back.
  • A check that fails on only some instances, eg one that times out under load, takes those instances out of the load balancer, up to half of them, and moves their traffic to the rest.
  • A replaced instance may be killed rather than stopped gracefully, which costs the wait and the repeated work described in let the app stop gracefully.

Vox's own health checks, of its background work, its queues and jobs, and its deployment mode, are shown in the Nexus admin, not on this endpoint.

Let the app stop gracefully​

App Service restarts instances all the time: when you deploy, swap slots, change a setting, scale in, and when Azure updates the platform. How the application stops decides what that costs.

  • A host that stops gracefully finishes the checks it started and releases what it claimed, so another instance takes the work over at once and nothing is done twice.
  • A host that's killed keeps its claims until they expire after 2 minutes. Until then nobody works on them, eg 500 products waiting for recalculation after a price import, and afterwards another instance does the whole batch again, so the application's own side effects run twice. Nothing is lost, see how the work spreads over hosts.

On Linux, start the app with exec​

On Linux, App Service starts a code-deployed .NET application with a startup script that runs dotnet MyShop.Api.dll as a child process of a shell. When App Service stops the app, it sends the stop signal, SIGTERM, to that shell, which doesn't pass it on. The application never hears that it's stopping: ApplicationStopping isn't raised, hosted services aren't stopped, and the process is killed when the platform stops waiting.

Set the app's startup command so that the shell replaces itself with the application:

exec dotnet MyShop.Api.dll

Use the name of the application's main assembly. Set it in the stack settings' Startup command, under Settings > Configuration > General settings, or with:

az webapp config set --resource-group shop-rg --name shop-api --startup-file "exec dotnet MyShop.Api.dll"

Set it on every slot and on every app, eg also a separate processing app.

Give the app time to stop​

After the stop signal, App Service waits a short time before it kills the process. For custom containers, the app setting WEBSITES_CONTAINER_STOP_TIME_LIMIT sets how long, in seconds: 5 by default, at most 120. Microsoft doesn't document whether it applies to the built-in .NET stack too, but setting it does no harm. Give Vox time to finish the checks it started, eg 30 seconds:

az webapp config appsettings set --resource-group shop-rg --name shop-api --settings WEBSITES_CONTAINER_STOP_TIME_LIMIT=30

.NET waits up to HostOptions.ShutdownTimeout, 30 seconds by default, for the application to stop. Keep it a little shorter than the App Service limit, so the application finishes stopping before the platform kills it:

Program.cs
builder.Services.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(25));

On Windows, the ASP.NET Core Module waits up to its shutdownTimeLimit, 10 seconds by default, for the application to stop when a deployment takes it offline with app_offline.htm.

Check that it works​

Turn on the app's logging in Monitoring > App Service logs, restart the app and watch its log stream, eg with az webapp log tail --resource-group shop-rg --name shop-api. A graceful stop logs Application is shutting down... before the instance starts again, as long as the Microsoft.Hosting.Lifetime category logs at Information, as the ASP.NET Core templates set it. Without the startup command there's no such line: the next thing in the log is the new start.

note

A graceful stop isn't guaranteed when Linux instances are scaled in. An instance that's killed costs the 2-minute wait and the repeated batch described above, nothing more.

Configuration and secrets​

App settings are configuration. A nested key's : becomes __ in an app setting's name, eg Vox__Deployment__BuildId for Vox:Deployment:BuildId. Connection strings go in Connection strings, eg Vox for ConnectionStrings:Vox, with the type SQLAzure for Azure SQL Database and Custom for PostgreSQL.

Keep secrets in Key Vault. Refer to a secret from an app setting or a connection string, eg the deployment key:

Vox__Deployment__ApiKey = @Microsoft.KeyVault(SecretUri=https://shop-vault.vault.azure.net/secrets/vox-deployment-key)

The app reads the vault with its managed identity, which needs the Key Vault Secrets User role on the vault, or the "Get" permission on secrets, see security.

Both slots use the production database. Blue and green share the Vox database while one hands the work over to the other, so don't give the staging slot a test database through a deployment slot setting. Use a separate app for a test environment.

The deployment id travels with the package. Write it into the package, see identities. If you set it as an app setting instead, don't mark it as a deployment slot setting, since those stay with the slot when it's swapped.

Scale out​

More than one instance, or a slot running next to production, means Vox runs in more than one process, on more than one machine. Each of these is needed from the second instance on:

  • A cross-machine broker, eg database polling or Azure Service Bus, see a cross-machine broker.
  • Worker ids need no setting. They default to the app's name and WEBSITE_INSTANCE_ID, eg shop-api-7f3a…, which survive a restart and differ per instance, also between an API app and a processing app that run on the same VM instances of one plan, see worker ids.
  • Data Protection keys in a store that every slot shares, see the next section.

Data Protection keys​

On App Service, ASP.NET Core keeps the Data Protection keys in a folder that all instances of a slot share, but each slot has a key ring of its own, and after a swap the production app keeps using the key ring it had in staging. Vox protects preview grants, image preview URLs and the signed content URLs of assets with these keys, so with the default an editor's preview link made by blue doesn't open on green while both run, and stops working after the swap.

Keep the keys where every slot reads them, with the same application name, eg in the Vox database with the Microsoft.AspNetCore.DataProtection.EntityFrameworkCore package and a registered DbContext that implements IDataProtectionKeyContext, whose DataProtectionKeys table you create with its migrations:

Program.cs
builder.Services.AddDataProtection()
.SetApplicationName("shop-api")
.PersistKeysToDbContext<ShopKeysContext>();

Azure Blob Storage, with PersistKeysToAzureBlobStorage, works as well. Protect the keys at rest with ProtectKeysWithAzureKeyVault, see keys that Vox hosts hold.

Asset files​

Assets stored on disk default to App_Data/assets in the application's directory, which a deployment replaces and each slot has its own copy of. Mount an Azure Files share in every slot, eg at /mounts/vox, and give each store a folder of its own on it, eg Vox:Assets:RootPath set to /mounts/vox/assets and Vox:Images:RenditionRootPath to /mounts/vox/renditions, so every instance and both releases read the same files, see assets.

Or keep them in Azure Blob Storage, which needs no mount and works with a managed identity, see Azure Blob Storage. Both slots use the same container.

Release with deployment slots​

A blue/green release with a staging slot. Blue, the current release, runs in production, and the pipeline releases green:

  1. Start the staging slot and deploy green to it, with a new deployment id written into the package. Green's instances start in standby: they migrate the model and accept writes, but don't run any background work.

  2. Activate green through the staging slot's URL, eg https://{staging host}/vox/api/deployment, and wait until the activation completed, see activate from the pipeline. Blue's instances finish what they're doing and hand the work over, and green's take it over. Blue keeps accepting writes, and green processes them.

  3. Swap the slots. While the swap warms green up, which commonly takes a minute or more, traffic still reaches blue, eg customers adding to their carts, and green processes those writes. A swap restarts the instances of a slot whose deployment slot settings change, which is one more reason to stop gracefully.

  4. Stop the staging slot, where blue now runs, retired:

    az webapp stop --resource-group shop-rg --name shop-api --slot staging

A separate processing app gets the same deployment id as the API app of the same release. Deploy and swap both before the activation, so the activation waits for both, and stop both staging slots afterwards.

Roll back by redeploying, not by swapping back. A swap back sends the traffic to blue, which is retired, while green's code keeps doing the background work. Deploy the old version again instead, see rolling back.

What an activation does, the modes and recovery from a failed activation are the same on every platform, see deployments.

Limits​

  • Studio's local rollout runner can't run on App Service, since App Service starts the application process itself, see Studio local rollout. Use a hosted repository target and the pipeline.
  • A scale-in on Linux may still kill an instance without a graceful stop, see the note above.