Publishing and Deployment: Going Live

Publishing and Deployment: Going Live in C#: A band's rehearsal room is a forgiving place. The amp in the corner is the amp you always use, the settings are…

The Analogy: Packing the Road Case

A band's rehearsal room is a forgiving place. The amp in the corner is the amp you always use, the settings are whatever they were last Tuesday, and if something buzzes somebody reaches round the back and wiggles a cable. dotnet run is that room. It has your source, your SDK, your launchSettings.json, your local database, and a hundred small conveniences you have stopped noticing. None of them are coming with you.

dotnet publish is packing the road case. Everything the show needs has to go in the case now, on the floor of the rehearsal room, while you can still see what is missing. Anything you forget simply does not exist at the venue: the config file you assumed was there, the fonts, the locale data, the certificate. That is why a publish is not "a build with a different flag" but a decision about what travels — the compiled assemblies, the dependency manifest, the runtime configuration, the static files — and what stays behind, which is your entire toolchain.

Then there is the question of the piano. Some venues have one, and if yours is the right model you can travel light: that is a framework-dependent deployment, where the machine already has the .NET runtime installed and you ship only your own code. If you cannot trust the venue, you bring your own instrument: a self-contained deployment carries the runtime in the case, which is heavier but works on a box that has never heard of .NET. And if you want the load-in to be one flight case that nobody has to unpack, you go single-file, or trim and compile ahead of time so the case is smaller and opens faster.

Finally, the part every touring crew treats as sacred and every deployment forgets: the sound check. Doors do not open until someone has walked the stage, tapped each microphone and confirmed the desk is talking to the speakers. Health checks are that walk-through — live says the box is up, ready says it is actually able to serve — and a load balancer that sends traffic before ready passes is a venue that opens the doors during the sound check. The other sacred rule is the end of the night: you finish the song you are playing before the lights come up. That is graceful shutdown, and getting it wrong is why users see one failed request every time you deploy.


Syntax or Core Structure

One command produces a deployable folder. The flags decide how much of .NET travels inside it.

# Framework-dependent: smallest output, needs the runtime installed on the target
dotnet publish -c Release -o out

# Self-contained: carries the runtime, runs on a machine with no .NET at all
dotnet publish -c Release -r linux-x64 --self-contained true -o out-linux

# One executable, trimmed of unused framework code
dotnet publish -c Release -r linux-x64 --self-contained true -o out-single \
    -p:PublishSingleFile=true -p:PublishTrimmed=true

Settings that belong in the project file rather than in whoever's shell history:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishReadyToRun>true</PublishReadyToRun>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

</Project>

Output: (abridged: banner lines, SDK versions, timings and absolute paths removed; annotations added)

$ dotnet publish -c Release -o out
  Determining projects to restore...
  Restore complete
  Shop -> bin/Release/net8.0/Shop.dll
  Shop -> out/

$ ls out
  Shop                       native launcher for this platform
  Shop.dll                   your compiled code
  Shop.pdb                   debug symbols
  Shop.deps.json             the dependency graph the runtime resolves at startup
  Shop.runtimeconfig.json    which framework version and GC settings to use
  appsettings.json           configuration that travelled with the build
  wwwroot/                   static files, if the project has any

Three of those files decide whether the application starts on a machine you have never logged into. Shop.dll is your code, but it is not executable on its own — the native launcher Shop (or Shop.exe) exists only to load the runtime and hand it that DLL, which is why dotnet Shop.dll is an equally valid way to start it. Shop.runtimeconfig.json names the framework version the app expects and any GC or threadpool settings; if the target box has 8.0.2 and this file demands 9.0, startup fails immediately with a readable error rather than crashing later. Shop.deps.json lists every assembly the runtime is allowed to load, so a NuGet package you referenced but never packed produces a resolution failure at load time, not a mysterious FileNotFoundException on page three of the checkout.

Note what is not in the folder: no .cs files, no bin/Debug, no launchSettings.json, no user secrets, and no appsettings.Development.json unless you asked for it. The publish output is the contract, and the fastest way to find out what your application secretly depended on is to run that folder on a clean machine.


Technical Depth: Modes, Environments and Going Live Safely

Choosing what travels

ModeSizeNeeds .NET installedStartupGood for
Framework-dependentsmallest, a few MByes, matching major versionnormalcontainers on a .NET base image, managed hosts
Self-containedtens of MBnonormallocked-down servers, appliances, side-by-side versions
Single filesame, one artifactnoslightly slower first runcopy-one-thing deployments, CLI tools
ReadyToRunlargerdependsfaster startupshort-lived processes, cold-start sensitive APIs
Trimmedsmallernonormalself-contained apps with few dynamic dependencies
Native AOTsmallest self-containednofastest, lowest memoryminimal APIs, functions, sidecars

Trimming and AOT both remove code the compiler cannot prove you use, and both therefore break anything that finds types by name at run time — reflection-heavy serializers, Activator.CreateInstance on a string, some DI conventions, EF Core's model builder. PublishTrimmed will warn about the ones it can see; the ones it cannot are why a trimmed build must be smoke-tested, not just compiled. AOT additionally requires source-generated JSON and rules out anything that emits IL at run time.

A runtime identifier names the target: linux-x64, linux-musl-x64 for Alpine, linux-arm64 for Graviton and Apple silicon containers, win-x64, osx-arm64. Publish for the RID the machine actually runs; the most common deployment failure of this kind is an x64 artifact landing on an arm64 node, which fails with an exec format error that mentions nothing about architecture.

The environment decides the behaviour, not the build

One artifact should run in every environment. What differs is the surroundings:

VariableEffect
ASPNETCORE_ENVIRONMENTpicks appsettings.{value}.json, and drives IsDevelopment() checks
ASPNETCORE_URLSwhich addresses and ports Kestrel binds, e.g. http://+:8080
ASPNETCORE_HTTP_PORTSsimpler port-only form, honoured by the official container images
DOTNET_ENVIRONMENTthe same idea for non-web hosts
Section__Keyoverrides any configuration key; the double underscore replaces the colon

Building a separate artifact per environment defeats the purpose of testing one: whatever you verified in staging is then not the thing that reaches production. Build once, promote the same bytes, change only the environment.

Two details bite in production. First, the Development environment enables the developer exception page, which prints stack traces and configuration to anyone who triggers an error — an environment variable typo is therefore an information disclosure bug. Second, behind a reverse proxy or ingress the app sees the proxy's address and scheme unless you tell it otherwise:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

Without that, Request.IsHttps is false behind a TLS-terminating proxy, redirect URIs come out as http, and rate limiting by IP sees one client. With it, restrict KnownProxies or KnownNetworks to the addresses you actually trust, because those headers are attacker-supplied everywhere else.

Sound check: liveness, readiness and startup

builder.Services.AddHealthChecks()
    .AddCheck("process", () => HealthCheckResult.Healthy(), tags: new[] { "live" })
    .AddCheck<DatabaseCheck>("database", tags: new[] { "ready" });

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = registration => registration.Tags.Contains("live")
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = registration => registration.Tags.Contains("ready")
});
ProbeQuestionIf it failsMust not check
Livenessis this process wedged?the orchestrator restarts itdependencies you cannot fix by restarting
Readinessmay it receive traffic now?it is removed from the load balancernothing; this is where dependencies belong
Startuphas it finished booting?restarts are deferred, not triggeredanything slow to evaluate repeatedly

The distinction is not pedantry. A liveness probe that pings the database will restart every healthy instance during a database outage, converting a degraded system into an outage of your own making. A readiness probe that checks nothing lets a brand-new instance take traffic before its caches, connection pools and JIT have warmed up, so every deploy shows up as a spike of slow requests.

Health endpoints should also be cheap and unauthenticated but unadvertised — a probe hit every two seconds must not run SELECT COUNT(*) over an audit table.

Finishing the song: graceful shutdown

When the orchestrator wants an instance gone it sends SIGTERM. ASP.NET Core responds by stopping the listener, letting in-flight requests finish, and running ApplicationStopping callbacks:

builder.Services.Configure<HostOptions>(options =>
{
    options.ShutdownTimeout = TimeSpan.FromSeconds(20);   // must exceed your slowest request
});

app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("draining"));

Three things make this actually graceful. Your shutdown timeout has to be longer than your slowest normal request, or the host kills the work anyway. Your readiness probe should start failing before the listener stops, so the load balancer stops sending new work while the old work drains — most platforms give you a preStop hook for exactly this. And background workers must honour the stoppingToken in BackgroundService.ExecuteAsync, because a loop that ignores it is the reason your pods take the full termination grace period to die.

A container that is not embarrassing

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY *.csproj .
RUN dotnet restore                      # cached unless the csproj changes
COPY . .
RUN dotnet publish -c Release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
USER $APP_UID
ENV ASPNETCORE_HTTP_PORTS=8080
EXPOSE 8080
ENTRYPOINT ["dotnet", "Shop.dll"]

The two stages matter: the SDK image is roughly ten times the size of the runtime image and contains a compiler, so shipping it to production means shipping build tooling to production. Copying only the project file before restore means a code-only change reuses the cached package layer. USER $APP_UID runs as the non-root user the official images define, and setting the port explicitly avoids the historical surprise that .NET 8 images listen on 8080 while older ones listened on 80.

The rest of going live

  • Database migrations belong to the deployment, not to startup. Database.Migrate() in Program means every instance races to alter the schema during a rolling update, and a failed migration takes the application down with it. Run dotnet ef database update or a generated SQL script as a separate, gated step, and make each migration backward compatible so the old version keeps working during the overlap.
  • Rollout strategy decides your migration rules. Rolling and blue-green updates both run two versions at once, which means "add a nullable column" is safe and "rename a column" is two deployments: add and write to both, then remove.
  • Configuration you cannot change without a rebuild is a trap. Feature flags, timeouts and connection strings belong in configuration; IOptionsMonitor<T> gives you live reloads where the platform supports them.
  • Log to standard output as structured JSON and let the platform collect it. Files inside a container are lost on restart, and Console.WriteLine without structure is unsearchable at 3am.
  • Instrument before you need to. AddOpenTelemetry().WithTracing(...).WithMetrics(...) plus the ASP.NET Core and HttpClient instrumentation gives you request rates, latency percentiles and traces across services for a few lines of setup.
  • Keep the artifact reproducible. Pin the SDK with global.json, restore with a lock file, and tag the image with the commit SHA rather than latest, so "which build is running?" has an answer.

Real World Example: A Deploy Nobody Noticed

The two events that produce visible errors during a deployment are traffic arriving before an instance is ready, and traffic being cut off while an instance is still working. The program below builds one host with a proper readiness gate and a slow endpoint, then walks the whole life cycle in a single process: cold, warm, serving, draining, gone.

using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.WebHost.UseUrls("http://localhost:5220");

builder.Services.AddSingleton<WarmupState>();
builder.Services.AddHealthChecks()
    .AddCheck("process", () => HealthCheckResult.Healthy(), tags: new[] { "live" })
    .AddCheck<WarmupCheck>("warmup", tags: new[] { "ready" });

WebApplication app = builder.Build();

// Liveness answers "is the process wedged", so it checks nothing external.
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = registration => registration.Tags.Contains("live")
});

// Readiness answers "may I have traffic", so it checks the warm-up.
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = registration => registration.Tags.Contains("ready")
});

app.MapGet("/orders/1", () => new OrderStatus(1, "packed"));

app.MapGet("/slow", async () =>
{
    await Task.Delay(500);                     // a request that outlives the shutdown signal
    return "finished while draining";
});

app.Lifetime.ApplicationStopping.Register(() => Console.WriteLine("lifetime: ApplicationStopping fired"));

await app.StartAsync();

using HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:5220") };

await Probe("live", "/health/live");
await Probe("ready", "/health/ready");

// Whatever the real warm-up is: caches, connection pools, a schema version check.
app.Services.GetRequiredService<WarmupState>().Ready = true;
Console.WriteLine("warm-up finished");

await Probe("ready", "/health/ready");
await Probe("orders/1", "/orders/1");

Task<HttpResponseMessage> inFlight = client.GetAsync("/slow");
await Task.Delay(100);

Console.WriteLine("shutdown requested");
Task stopping = app.StopAsync();

HttpResponseMessage slowResponse = await inFlight;
await stopping;

Console.WriteLine($"in-flight /slow finished with {(int)slowResponse.StatusCode}");

try
{
    await client.GetAsync("/health/live");
    Console.WriteLine("after shutdown: request unexpectedly succeeded");
}
catch (HttpRequestException ex)
{
    Console.WriteLine($"after shutdown: {ex.GetType().Name}");
}

async Task Probe(string label, string path)
{
    HttpResponseMessage response = await client.GetAsync(path);
    string body = await response.Content.ReadAsStringAsync();

    Console.WriteLine($"{label,-10} {(int)response.StatusCode} {body}");
}

sealed class WarmupState
{
    public volatile bool Ready;
}

sealed class WarmupCheck : IHealthCheck
{
    private readonly WarmupState _state;

    public WarmupCheck(WarmupState state) => _state = state;

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default) =>
        Task.FromResult(_state.Ready
            ? HealthCheckResult.Healthy("caches primed")
            : HealthCheckResult.Unhealthy("still warming up"));
}

record OrderStatus(int Id, string Status);

Output:

live       200 Healthy
ready      503 Unhealthy
warm-up finished
ready      200 Healthy
orders/1   200 {"id":1,"status":"packed"}
shutdown requested
lifetime: ApplicationStopping fired
in-flight /slow finished with 200
after shutdown: HttpRequestException

The first two lines are the state every deployment passes through and most deployments ignore: the process is alive but not ready. Liveness returns 200 because the process is running and answering; readiness returns 503 because the warm-up has not finished. Those two answers go to two different audiences — the orchestrator reads liveness and would restart the instance if it failed, the load balancer reads readiness and holds traffic back while it fails. Point both probes at the same endpoint and you must choose which mistake to make: restart instances during a dependency outage, or send requests to an instance that is not ready to serve them.

Once the flag flips, readiness turns green and ordinary traffic works. Note how cheap the ready check is — it reads a boolean. The expensive part, whatever the real warm-up is, ran exactly once during startup; a readiness probe hit every two seconds must never repeat that work, which is why "readiness includes dependencies" means "readiness reads the result of checking dependencies", not "readiness re-queries the database on every probe".

The three lines after shutdown requested are graceful shutdown doing its job. StopAsync stopped the listener, fired ApplicationStopping, and then waited: the /slow request that was already in progress finished with 200 instead of a reset connection. That waiting is bounded by ShutdownTimeout, so an endpoint that takes 30 seconds under a 20 second timeout would still be cut off mid-response — matching the timeout to your slowest real request is the whole configuration story. Notice also that the stopping callback fires at the start of the drain, not the end, which is the hook you use to flush buffers or tell a service registry you are leaving.

The last line is the reason ordering matters. Once the listener is gone the process cannot answer politely — a new connection gets HttpRequestException, not a courteous 503. Nothing inside the application can fix that, so the load balancer has to have stopped sending traffic before the signal arrived. The sequence that nobody notices is: fail readiness (a preStop hook), let the load balancer drain, then SIGTERM, then in-flight requests finish, then exit — while the replacement instance stays out of rotation behind its own readiness gate until it is warm.


Common Mistakes

  1. Publishing the Debug configuration. dotnet publish without -c Release ships unoptimised code with debug assertions enabled. It works, it is just slower and noisier than the build you tested.
  2. Building a different artifact per environment. If staging and production are separate builds, staging proved nothing about the bytes that reached production. Build once, promote the same artifact, vary only configuration.
  3. Leaving ASPNETCORE_ENVIRONMENT=Development on a public server. The developer exception page then prints stack traces, connection string names and environment details to anyone who can cause an error.
  4. A liveness probe that checks the database. During a database blip every instance fails liveness and gets restarted, so a recoverable dependency problem becomes a full outage with cold caches.
  5. No readiness gate at all. New instances take traffic while pools, caches and JIT are cold, which is why "the site is slow for a minute after every deploy" is so common.
  6. Running EF Core migrations from application startup. During a rolling update several instances race to change the schema, and a migration failure now also means the application will not start.
  1. Shipping the SDK image, running as root, tagging latest. The first triples your image size and puts a compiler in production, the second hands an attacker the container, and the third makes "which build is live?" unanswerable.
  2. A shutdown timeout shorter than your slowest request, or a BackgroundService that ignores stoppingToken. Both turn every deploy into a handful of truncated responses and a process the platform has to kill.
  3. Publishing for the wrong runtime identifier, or trimming without smoke-testing. An x64 artifact on arm64 fails with an exec format error, and a trimmed build fails only on the code path that used reflection.
  4. Depending on the container's filesystem or clock-in-place state. Files written next to the binary vanish on restart, log files inside a container are unreadable after a crash, and in-memory session state breaks the moment there are two instances.

Best Practices

  • Build the artifact once in Release, tag it with the commit SHA, pin the SDK with global.json, and promote that exact image or folder through every environment.
  • Run the published output in CI, not just dotnet test against the source tree — smoke-starting out/ catches the missing file, the wrong RID and the trimming casualty before a human sees them.
  • Use a multi-stage Dockerfile onto the runtime image, run as the non-root $APP_UID, set the port explicitly, and copy the project file before restoring so package layers stay cached.
  • Give the platform all three probes with honest scopes: liveness for "restart me", readiness for "route to me", startup for "wait for me". Keep them cheap and never authenticated by a system that might be down.
  • Make shutdown deliberate: fail readiness first via a preStop hook, set ShutdownTimeout above your p99 request, and pass stoppingToken through every background loop and long-running call.
  • Treat schema changes as a separate, gated deployment step, and keep every migration compatible with the version currently running, because rolling updates always run two versions at once.
  • Log structured JSON to standard output, add OpenTelemetry tracing and metrics for ASP.NET Core and HttpClient, and make sure a trace id appears in both the log line and the error response.
  • Rehearse the rollback. Know the exact command, keep the previous image, and put behaviour you cannot roll back — a schema drop, a one-way data fix — behind a feature flag instead.

Practice Exercises

  1. Publish the same project three ways — framework-dependent, self-contained single file, and trimmed — then record the output size and the cold start time of each, and run all three from a directory on a machine with no SDK installed.
  2. Extend the real world example with a togglable fake dependency behind the readiness check. Prove from the transcript that failing the dependency removes the instance from service while liveness still returns 200 and the process is never restarted.
  3. Write the Dockerfile from this lesson for that project and verify four things: the image runs as a non-root user, it listens on the port you set, it is a fraction of the SDK image's size, and docker stop lets an in-flight /slow request finish. Then shorten ShutdownTimeout below the request duration and show what changes.
  4. Add two BackgroundService implementations, one that ignores stoppingToken and one that honours it, and measure how long shutdown takes in each case. Explain which platform setting decides the difference between "drained" and "killed".