Running .NET in Kubernetes: Health Checks, Config, and Graceful Shutdown
Running .NET in Kubernetes: health check endpoints, env-var configuration with __ separators, SIGTERM graceful shutdown, and memory behavior under limits.
__ separator maps them into your options classes), and drain gracefully when SIGTERM arrives, finishing in-flight requests before the container dies. ASP.NET Core supports all three natively: AddHealthChecks/MapHealthChecks, the default configuration providers, and the host’s stopping token plus HostOptions.ShutdownTimeout.The incident that introduces this topic is always a deploy: a rolling update starts, pods terminate, and a spike of 502 Bad Gateway appears in the client’s logs. The app was fine; it was killed mid-request. Kubernetes sent SIGTERM, the container died instantly because nothing waited for in-flight requests to finish. The load balancer was still routing traffic to a corpse. Everything below is about making the pod’s death, and its life, unremarkable.
Running .NET in Kubernetes means meeting the platform’s contract: health endpoints for probes, environment variables for configuration, and SIGTERM for shutdown. The health checks documentation, the configuration fundamentals, and the container image built in the Dockerizing guide are the prerequisites. The deep platform mechanics, probe types and tuning, ConfigMap and Secret wiring, resource requests and limits, belong to the Kubernetes guide: the guides on probes, ConfigMaps and Secrets, and requests and limits cover them.
The examples run the TaskApi image from the container guide: non-root, listening on 8080, stdout logging per the Serilog guide (which is what makes logs collectable here at all).
Running .NET in containers through several platform migrations taught me this: .NET is an unusually good container citizen when you wire its built-in machinery to the platform’s. Every problem below has a first-class hook in the framework; the bugs come from not using them.
Health check endpoints: answer the platform honestly
Kubernetes probes your container over HTTP, and ASP.NET Core has a purpose-built endpoint for exactly that. Wiring it is two lines:
builder.Services.AddHealthChecks()
.AddDbContextCheck<TaskApiContext>("database"); // is the DB reachable?
var app = builder.Build();
app.MapHealthChecks("/health");
The /health path returns 200 while every registered check passes and 503 when one fails, with the response body listing which check failed. AddDbContextCheck is the sensible default for the TaskApi: it runs a cheap query. As a result, the probe answer reflects the app’s actual ability to serve, beyond the process being alive. Custom checks implement IHealthCheck for anything else the service depends on:
public sealed class StorageHealthCheck(IOptions<StorageOptions> options) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken ct = default)
{
var healthy = await CanReachStorageAsync(options.Value, ct);
return healthy
? HealthCheckResult.Healthy()
: HealthCheckResult.Unhealthy("storage unreachable");
}
}
Two real design rules: separate liveness-style checks (the process can serve at all) from readiness-style checks (dependencies are reachable), using tags and mapped paths (MapHealthChecks("/health/live", ...) versus /health/ready), and keep the checks cheap, because the platform calls them continuously. The mapping between these endpoints and the platform’s probe types, thresholds, and tuning is deep coverage that belongs to the Kubernetes guide’s probes guide. The same /health endpoint also serves the App Service health check in the Azure guide.
Configuration: environment variables with __ separators
Everything the platform tells your app, it tells through environment variables, and the default ASP.NET Core configuration providers already read them. The one syntax to know is the separator: a double underscore maps to a nested key.
TaskApi__DefaultOwner=imran -> TaskApi:DefaultOwner
TaskApi__Limits__MaxTasks=1000 -> TaskApi:Limits:MaxTasks
Jwt__Issuer=https://taskapi.example -> Jwt:Issuer
That is the entire integration: the options-pattern classes bind from configuration, configuration reads environment variables, and Kubernetes injects them. The platform side, defining ConfigMaps and Secrets so the values reach the pod, is its own discipline, covered in the Kubernetes guide’s ConfigMaps and Secrets guide. From .NET’s perspective, there is nothing to install, only names to keep consistent.
SIGTERM: the platform’s goodbye
When a pod terminates, the sequence is fixed. Kubernetes sends SIGTERM to the container’s process (PID 1, which is your app in the .NET images), waits the grace period (30 seconds by default), then SIGKILLs. What your app does with SIGTERM is the whole graceful shutdown story:
SIGTERM
|
v
the host's stopping token cancels
|
+----------+-----------------+
| | |
Kestrel stops hosted your code, via
accepting new services IHostApplicationLifetime
requests stop OnApplicationStopping
|
in-flight requests finish
|
HostOptions.ShutdownTimeout elapses, or
the app is done, whichever comes first
The .NET host does the heavy part for you: Kestrel stops accepting new connections and finishes the requests in flight. Every hosted service’s stopping token fires, the same token the background jobs guide runs its workers on. Your code joins the flow through IHostApplicationLifetime for anything the host does not cover:
// in Program.cs, after the app is built:
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
{
// flush buffers, close long-lived connections, drain queues
});
app.Run();
HostOptions.ShutdownTimeout: fit your drain in the grace period
The host waits a fixed time for everything to finish before it gives up, set by HostOptions.ShutdownTimeout with a 30-second default. The arithmetic that matters: your app’s shutdown timeout must be comfortably shorter than the pod’s grace period, because the platform’s SIGKILL does not negotiate:
builder.Services.Configure<HostOptions>(options =>
options.ShutdownTimeout = TimeSpan.FromSeconds(25));
// grace period default: 30s. App timeout: 25s. Slack: 5s.
If your app can genuinely need longer (large in-flight uploads, slow batch drain), the grace period itself is configurable on the pod. The pairing of the two numbers is part of the deployment spec, which the Kubernetes guide covers. What .NET owes is a drain time that finishes inside whatever you promised.
The illustrative manifest
One manifest shows the whole contract (24 lines, illustrative; the platform-side fields get their own treatment in the Kubernetes guide):
apiVersion: apps/v1
kind: Deployment
metadata:
name: taskapi
spec:
replicas: 3
selector:
matchLabels: { app: taskapi }
template:
metadata:
labels: { app: taskapi }
spec:
containers:
- name: taskapi
image: registry.example/taskapi:1.0.0 # versioned, never latest
ports: [{ containerPort: 8080 }]
env:
- name: TaskApi__Limits__MaxTasks
value: "1000"
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
livenessProbe:
httpGet: { path: /health/live, port: 8080 }
terminationGracePeriodSeconds: 30
Three .NET decisions are visible there. The image is the multi-stage build from the container guide (port 8080, non-root), the __ environment variable feeds the options pattern. Both probes hit the health endpoints. Resource requests and limits are deliberately absent here. This is because sizing is its own topic: the deep treatment of requests and limits belongs to the Kubernetes guide.
.NET memory behavior under container limits
The .NET runtime is container-aware: when the container has a memory limit, the garbage collector sizes its heap hard limit from that value instead of the machine’s memory, and the visible CPU count influences how the GC balances its work. In practice, that means a pod with a limit is not a pod running a workstation-class desktop heap; the runtime adapts within the box it is given.
Two operational consequences follow. First, set limits deliberately (with the sizing guidance in the Kubernetes guide), because the GC behavior and OOMKilled outcomes follow from the number you choose. Second, watch the OOMKilled status for pods that die from memory pressure: it looks like a crash from inside. Still, the container metrics and restart reason tell the truth. The garbage collector configuration reference documents the knobs, including container-aware defaults, so you tune with facts rather than folklore.
How real systems do this
- One health endpoint, every platform. The same
/healthmapping answers Kubernetes probes, the App Service health check path, and load balancers, so “is it healthy” is a single implementation everywhere. - Drain time is measured, not guessed. Teams know their p99 request duration and their queue depth, set the shutdown timeout above the first and the grace period above both, and verify with a deploy under load.
- The fleet is managed as code. Manifests live in the repository and reach the cluster through a pipeline or a GitOps tool. Deep coverage of GitOps with Argo CD and Flux belongs to the Kubernetes guide.
A rollout I remember went exactly as this guide predicts when the defaults were left alone: pods terminated instantly on SIGTERM because an early prototype had the app crash-loop on purpose during shutdown testing (a shortcut someone forgot to remove), and every deploy sprayed 502s across the load balancer for the two minutes it took the rollout to finish. The fix was deleting the shortcut and trusting the host’s built-in drain, and the next rollout was invisible to clients. What I took from it: the platform’s contract is generous by default, but only code that honors SIGTERM gets the grace period it promises.
Decision framework: the .NET side of the contract
- What should the platform probe? A real endpoint:
/healthwith dependency checks for readiness, a cheap liveness path for the process itself. Never the homepage, and never an endpoint that depends on something a probe should not kill the pod over. - How long can a request legitimately take? Set
ShutdownTimeoutabove your worst realistic in-flight request, and the pod’s grace period above that; measure before choosing either number. - What must happen on SIGTERM? Whatever the process owns: buffered writes flushed, long-lived connections closed, queues drained, all through the stopping token and
ApplicationStopping. Anything not on those hooks is not going to happen. - How does configuration arrive? Environment variables with
__separators, names matching the options classes, values delivered by the platform’s mechanisms (ConfigMaps, Secrets); no files baked into images. - What memory limit does the app get? One chosen deliberately, with the knowledge that the GC sizes itself from it. Pair it with alerts on container memory and restarts, and treat OOMKilled as a sizing signal, not bad luck.
When NOT to customize
- Do not hand-roll probe endpoints. A controller returning 200 with a “healthy” string re-implements the health checks library minus the status codes, the checks, and the body; use
MapHealthChecks. - Do not put heavy work on the stopping hook.
ApplicationStoppingruns inside the shutdown budget. Flushing a large buffer is its job, running a batch job is not (that belongs to the background jobs pattern and its own lifecycle). - Do not tune GC blindly under limits. The defaults are container-aware. Change the GC knobs only with a measured reason, and prefer adjusting the limit over configuring the collector.
Common mistakes
- Probing the homepage. A rendered page proves rendering, not dependencies, and slow probes count as failures. A tagged health path is the real answer.
- Shutdown timeout longer than the grace period. The app is SIGKILLed mid-drain, producing exactly the 502 storm the timeout was meant to prevent. Keep app time strictly inside platform time.
- Ignoring the stopping token in custom work. Background loops that never check it block shutdown for the full budget. The token is the contract for every long-running piece of your process.
- Configuration baked into the image. Environment values in the image defeat the point of platform-driven configuration; images stay environment-neutral.
- Hardcoded port assumptions. The container listens on 8080 by default. Probes and Services must agree with the app, and the image documentation is where that agreement lives.
- Treating OOMKilled as a crash. Memory-limit deaths look like crashes from the app’s perspective. The restart reason is the diagnosis, and the fix is sizing, not retries.
Key takeaways
- Kubernetes asks three things of a .NET app: a health endpoint, configuration from environment variables, and graceful SIGTERM handling, and the framework provides all three natively.
AddHealthChecksplusMapHealthChecksgives probe paths with real checks (AddDbContextCheck, customIHealthCheck), split liveness and readiness with tags and separate paths.- Environment variables with
__separators bind straight into options classes; the platform supplies values, the app only keeps names consistent. - SIGTERM cancels the host’s stopping token. Kestrel drains, hosted services stop, custom hooks run via
IHostApplicationLifetime, all insideHostOptions.ShutdownTimeout(default 30 seconds), which must fit the pod’s grace period. - The manifest is 24 illustrative lines: versioned image, port 8080,
__variable, both probes on health paths; probe tuning, ConfigMaps, and sizing belong to the Kubernetes guide. - The runtime is container-aware: GC sizing follows memory limits and CPU counts, so limits are a deliberate decision and OOMKilled is a sizing signal.
FAQ
How does a .NET app handle SIGTERM in Kubernetes?
The .NET host receives SIGTERM and cancels its stopping token: Kestrel stops accepting new requests and finishes the ones in flight, hosted services receive cancellation, and hooks registered on IHostApplicationLifetime run custom drain code. The host waits up to HostOptions.ShutdownTimeout for all of it, so keep that value inside the pod’s termination grace period.
What is an ASP.NET Core health check endpoint?
A mapped route that reports application health: register checks with AddHealthChecks, including dependency checks like AddDbContextCheck, and map them with MapHealthChecks. The endpoint returns 200 when all checks pass and 503 when any fails. Tags let you split cheap liveness checks from dependency-based readiness checks on separate paths.
How do Kubernetes environment variables map to .NET configuration?
Directly: the default configuration providers read environment variables, and double underscores map to nested keys. So TaskApi__Limits__MaxTasks becomes TaskApi:Limits:MaxTasks in the options classes. No code or package is needed; keeping variable names aligned with the configuration keys is the only discipline.
What is HostOptions.ShutdownTimeout for?
It caps how long the application host waits for graceful shutdown, with a default of 30 seconds. In a container, it must fit within the platform’s termination grace period, or the pod is SIGKILLed mid-drain. Teams set it above their worst realistic in-flight request duration and below the grace period.
How does .NET garbage collection behave under container memory limits?
The runtime is container-aware: with a memory limit set, the GC sizes its heap hard limit from the container limit rather than host memory, and the visible CPU count influences GC behavior. Set limits deliberately, watch container memory metrics, and read OOMKilled restarts as a sizing problem rather than an application crash.
Answer the probes, honor the signal
The container guide ships the image, this page wires the app to the platform. The last guide in the series builds the pipeline that puts them together. Everything Kubernetes asks of .NET has a framework-native answer: health checks for probes, environment variables for configuration, and the stopping token for shutdown, with drain arithmetic that keeps deploys invisible to clients. The platform side continues in the Kubernetes guide; next here is CI/CD for .NET projects, and every guide lives on the .NET series index. The rule of thumb: the platform is always asking two questions, healthy? and done?. Wire the endpoints that answer them honestly and deploys become quiet.
Last updated on 4 December 2026