Covers a real migration of an existing ASP.NET Core API to Azure Container Apps or AKS: auditing for hidden state, baked-in config, file-based logs and ignored shutdown; containerising; externalising config and secrets with managed identity; probes, telemetry, resilience and scaling; and proving readiness with chaos and load tests.
I would tell it as a four-step story. Audit the app against twelve-factor and find the hidden state: files written to disk, in-memory session, Data Protection keys, appsettings.Production.json with secrets, log files and in-process scheduled jobs. Containerise with no behaviour change. Fix in order of risk: move state out (Blob Storage, Redis, shared keys), externalise config to env vars and Key Vault with managed identity, add probes and graceful shutdown, OpenTelemetry, resilience on outbound calls, and move scheduled jobs and EF migrations out of the web process. Then prove it: kill replicas under load, deploy during a load test with zero errors, and shift traffic gradually with a rollback path.
The trade-off: you can lift and shift into a container in a day, but the work that makes it safe to scale is the state and lifecycle changes, so budget for those.
"At [company] we had [an orders API on two App Service instances with ARR affinity turned on], and the goal was [moving to Azure Container Apps so it could scale with demand and deploy several times a day]. My first step was an audit, not a Dockerfile. I went through the code looking for anything that assumed one long-lived machine, and found [four things: invoice PDFs written to a local folder, session in memory, which only worked because of sticky sessions, Data Protection keys on local disk, and a
System.Threading.Timerthat sent a nightly report from inside the web app]. We also had [a connection string with a SQL password inappsettings.Production.json].I sequenced the work by risk. First, containerise with no behaviour change and run it in a test environment, so any later problem was ours, not Docker's. Second, state: files to Blob Storage, session to Redis, Data Protection keys to Blob Storage protected by Key Vault, and only then did we turn off sticky sessions. Third, config: the password went away entirely because we switched Azure SQL to managed identity; the other settings became environment variables and Key Vault references. Fourth, lifecycle and telemetry: startup, readiness and liveness probes,
ShutdownTimeoutinside the grace period, OpenTelemetry to Application Insights. Fifth, the timer became a Container Apps job, because with three replicas it would have sent three reports.To prove readiness I ran a load test at [2x peak], killed replicas and did rolling deploys during it. [The first run showed 502s on deploy, which led us to add a preStop delay; the final runs had zero errors.] We cut over with [10% of traffic through Front Door for a week]. [The result: deploys went from monthly to daily, and infrastructure cost fell by about X%.] The lesson I took: containerising is easy; finding the state is the work."
| Finding | Symptom after scale-out | Fix |
|---|---|---|
| Files written under the app folder | 404s for files created on another replica; lost on redeploy | Azure Blob Storage, SAS or managed identity |
| In-memory session (sticky sessions hid it) | Users lose carts or get logged out | AddStackExchangeRedisCache + session |
| Data Protection keys on local disk | Antiforgery and cookie failures across replicas | PersistKeysToAzureBlobStorage + ProtectKeysWithAzureKeyVault |
Secrets in appsettings.Production.json |
Secret in the image and in git history | Managed identity, Key Vault; rotate the leaked secret |
| Log files with a rolling file sink | Logs lost with the container | JSON console + OpenTelemetry |
| In-process timers / Hangfire in the web app | Job runs N times, or is killed mid-run on scale-in | Container Apps job / Kubernetes CronJob / distributed lock |
Database.Migrate() at start-up |
Replicas race to migrate; slow start fails probes | Migration bundle as a pipeline step |
Windows-only dependencies (GDI+, System.Drawing) |
Fails on Linux images | Cross-platform library (e.g. SkiaSharp, ImageSharp licence check) |
| Step | Why in this order |
|---|---|
| 1. Containerise, no behaviour change | Isolates container problems from app changes |
| 2. Move state out | Must happen before removing sticky sessions or adding replicas |
| 3. Externalise config and secrets | Allows one image across environments |
| 4. Probes, shutdown, telemetry | Needed before the platform manages it and before cut-over |
| 5. Jobs and migrations out of the web process | Needed before scaling beyond one replica |
| 6. Prove and cut over gradually | Evidence and a rollback path |
The migrated API ran three to ten replicas with an HTTP-concurrency scale rule. Rolling deploys under a 2x-peak load test produced zero non-2xx responses after the preStop fix, p95 latency stayed at about 120 ms, and the nightly report ran exactly once a night as a scheduled job.
Checks whether the candidate has actually migrated a service and can explain the hidden problems, the order of work and how they proved it was ready.
Green flags
Red flags
App Service's ARR affinity (and any sticky load balancer) sends a user back to the same instance, so in-memory session, local files and per-instance Data Protection keys appear to work. The day you turn affinity off, scale in, or deploy, every hidden assumption fails at once. A good migration finds them in code before the platform finds them in production.
Before (sticky) After (stateless)
user A -> instance 1 (A's session) user A -> any replica -> Redis (session)
user B -> instance 2 (B's files) user B -> any replica -> Blob Storage (files)
keys: per-instance disk keys: Blob + Key Vault (shared)
Search the code and config for:
File., Directory., Path.Combine(env.ContentRootPath, IWebHostEnvironment.WebRootPath writesAddSession without a distributed cache, IMemoryCache used as a storeAddDataProtection without PersistKeysTo...Timer, PeriodicTimer, BackgroundService that must run onceDatabase.Migrate, EnsureCreatedappsettings*.json and in git history (gitleaks)app user since .NET 8; old code that binds port 80 or writes to the app folder fails.dotnet publish /t:PublishContainer builds an image without a Dockerfile; chiseled aspnet images have no shell, so debugging uses kubectl debug or Container Apps console with a debug image.Views/Home/index.cshtml versus Index.cshtml bugs appear here.| Option | When |
|---|---|
| Container Apps job (schedule trigger) / Kubernetes CronJob | Independent batch work; the cleanest choice |
Distributed lock (Azure Blob lease, SQL sp_getapplock) |
Work that must stay in-process but run once |
| Durable scheduler (Hangfire with SQL storage, Quartz clustered) | Many jobs with retries and dashboards |
If the API holds personal information, keep the Container Apps environment and data stores in Australia East (with Australia Southeast for DR) to meet customer data-residency expectations, and treat any secret found in git history as exposed: rotate it and assess under the Notifiable Data Breaches scheme if personal data could have been accessed.
dotnet publish /t:PublishContainer and run it with a read-only root file system.kubectl rollout restart and count errors before and after adding probes and a preStop delay.Before and after for the three changes that matter most: state, config and scheduled work. The "after" version needs the NuGet packages Azure.Identity, Azure.Storage.Blobs, Azure.Extensions.AspNetCore.DataProtection.Blobs, Azure.Extensions.AspNetCore.DataProtection.Keys, Microsoft.Extensions.Caching.StackExchangeRedis, Microsoft.EntityFrameworkCore.SqlServer and Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore.
// BEFORE: works on one sticky instance only
builder.Services.AddSession(); // in-memory: lost across replicas
builder.Services.AddDataProtection(); // keys on local disk, per instance
builder.Services.AddDbContext<OrdersDb>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Orders"))); // password in appsettings.Production.json
builder.Services.AddHostedService<NightlyReportTimer>(); // runs on every replica
app.MapPost("/invoices/{id:int}", async (int id, IWebHostEnvironment env, CancellationToken ct) =>
{
var path = Path.Combine(env.ContentRootPath, "invoices", $"{id}.pdf"); // local disk
await File.WriteAllBytesAsync(path, InvoiceRenderer.Render(id), ct);
return Results.Ok();
});
// AFTER (.NET 10): stateless, identity-based, scheduled work moved out
using Azure.Identity;
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
var credential = new DefaultAzureCredential(); // ManagedIdentityCredential in production
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddSession(); // now backed by Redis through IDistributedCache
var blobs = new BlobServiceClient(new Uri(builder.Configuration["Storage:BlobEndpoint"]!), credential);
builder.Services.AddSingleton(blobs);
builder.Services.AddDataProtection()
.SetApplicationName("orders-api")
.PersistKeysToAzureBlobStorage(blobs.GetBlobContainerClient("dataprotection").GetBlobClient("keys.xml"))
.ProtectKeysWithAzureKeyVault(new Uri(builder.Configuration["KeyVault:DataProtectionKeyId"]!), credential);
// Azure SQL with Entra ID authentication: the connection string names the auth method, not a password.
// Microsoft.Data.SqlClient uses the managed identity (or your developer login locally) to get a token.
// ConnectionStrings__Orders = "Server=tcp:orders.database.windows.net;Database=orders;Authentication=Active Directory Default;Encrypt=True"
// In production, prefer "Authentication=Active Directory Managed Identity;User Id=<client-id>" for a user-assigned identity.
builder.Services.AddDbContext<OrdersDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
builder.Services.AddHealthChecks().AddDbContextCheck<OrdersDb>(tags: ["ready"]);
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));
var app = builder.Build();
app.UseSession();
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });
app.MapPost("/invoices/{id:int}", async (int id, BlobServiceClient blobService, CancellationToken ct) =>
{
var blob = blobService.GetBlobContainerClient("invoices").GetBlobClient($"{id}.pdf");
await blob.UploadAsync(BinaryData.FromBytes(InvoiceRenderer.Render(id)), overwrite: true, ct);
return Results.Ok();
});
app.Run();
-- In the Orders database: let the app's managed identity in, with least privilege
CREATE USER [id-orders-api] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [id-orders-api];
ALTER ROLE db_datawriter ADD MEMBER [id-orders-api];
# The nightly report becomes a scheduled Container Apps job that runs once, not once per replica
az containerapp job create --name orders-nightly-report --resource-group rg-orders \
--environment cae-orders --trigger-type Schedule --cron-expression "0 14 * * *" \
--image myregistry.azurecr.io/orders-report:3f2a9c1 --replica-timeout 1800 \
--mi-user-assigned <identity-resource-id> # 14:00 UTC = 01:00 AEDT
Database.Migrate() at start-up across replicas. Why it is wrong: Replicas race, start-up is slow and probes fail during long migrations. Instead: Run an EF Core migration bundle as a pipeline step before the deploy.appsettings.Production.json into Key Vault and moving on. Why it is wrong: It is still in git history and in old images. Instead: Rotate it, or remove it with managed identity, and scan history.The senior signal in this story is sequencing and evidence. Anyone can write a Dockerfile; a senior engineer finds the assumptions an app makes about its machine, orders the changes so each is small and reversible, and proves readiness with tests that simulate what the platform will do (kill, deploy, scale). Also be honest about whether Container Apps or AKS is the right target: most single-team APIs are better served by Container Apps (or even App Service) than by running a Kubernetes cluster.
| Target | When it fits | Cost | When not to |
|---|---|---|---|
| App Service (containers) | One or a few web apps, simple scaling | Less control over sidecars, scale rules | Event-driven scaling, many services |
| Azure Container Apps | Several services, KEDA scaling, scale to zero, Dapr optional | Less control than raw Kubernetes | Need custom operators, CRDs, full mesh control |
| AKS | Platform team, many teams/services, custom networking | Cluster operations, upgrades, security | One team, a handful of services |
Measure success with deploy frequency, change failure rate, errors during deploys and cost per request before and after.
The twelve-factor app is a methodology, first published by Heroku in 2011, for building services that a platform can deploy, scale and replace without hand-holding. It is still the baseline that Azure Container Apps, AKS, App Service and AWS ECS assume. The factors that matter most for .NET are: config in the environment (ASP.NET Core's IConfiguration already layers environment variables over appsettings.json), backing services as attached resources (swap a connection string, not code), build, release, run (one immutable container image promoted through environments), stateless processes (no local disk or in-memory session state), disposability (fast start, graceful SIGTERM handling through the Generic Host) and logs as event streams (ILogger to stdout).
The trade-off: it is a set of strong defaults, not a law. Follow its intent, and bend factors such as "logs only" (use OpenTelemetry for all three signals) or secrets in plain environment variables (use Key Vault) where the platform gives you a better tool.
When a pod is stopped, Kubernetes removes it from Service endpoints and sends SIGTERM at the same time, then waits terminationGracePeriodSeconds (30 s by default) before SIGKILL. In .NET the Generic Host turns SIGTERM into IHostApplicationLifetime.ApplicationStopping; Kestrel stops accepting new connections and drains in-flight requests, and every IHostedService.StopAsync runs, all bounded by HostOptions.ShutdownTimeout (30 s by default since .NET 6, including .NET 10; it was 5 s before). Because endpoint removal propagates slowly, add a short preStop delay so the pod keeps serving until load balancers stop sending to it.
On the way up, a startup probe covers slow initialisation, a readiness probe decides whether the pod gets traffic, and liveness restarts only a truly stuck process. The trade-off: longer grace periods mean safer drains but slower deploys and scale-in.
I choose by how much platform the team wants to run:
The trade-off is control versus operations: each step towards AKS gives more control and more work. I start with the simplest option that meets the requirements and move only when I hit a concrete limit.
How to tell it (STAR)
**S:** We had an orders API on [two] App Service instances with sticky sessions, and the business wanted daily deploys and automatic scaling, so we moved to Container Apps. **T:** I led the migration and owned making sure customers noticed nothing. **A:** Before writing a Dockerfile, I audited the code and found four kinds of hidden state that sticky sessions had masked, plus a password in a config file. I containerised with no behaviour change, then moved files, session and Data Protection keys out, switched SQL to managed identity, moved the nightly timer into a scheduled job, and added probes and telemetry. I proved it with kill-and-deploy load tests and cut over through Front Door in stages. **R:** We went from [monthly] to [daily] deploys with [zero] customer-visible errors during cut-over, and the report ran exactly once a night.
Last updated 23 Nov 2026.