Skip to content
Tutorials Center
My learning

Topics

Lesson 143 of 182 ยท ASP.NET Core

Publishing and Deploying .NET Apps

Learn how to publish a .NET app: framework-dependent vs self-contained, single-file, Native AOT, Docker, health checks, production configuration and graceful shutdown.

Everything you have built so far runs on your machine because your machine has the .NET SDK, your configuration files and a developer certificate. A server in a data center has none of that by default. Deployment is the work of turning your source code into something that starts reliably somewhere else, finds its configuration, tells the platform whether it is healthy, and shuts down politely when asked.

This lesson follows that path. You will learn what dotnet publish produces, the choice between framework-dependent and self-contained output, when single-file and Native AOT make sense, how a Docker image fits in, and the runtime behaviors every production app needs: environments, layered configuration, health checks and graceful shutdown. The commands that need the dotnet CLI or Docker are shown read-only and labelled; everything that is about runtime behavior you can run right here.

Build versus publish

dotnet build compiles your project into bin/Debug/net10.0/ so you can run and debug it next to the SDK. dotnet publish produces a self-contained folder of files you can copy to a server: your compiled assemblies, their dependencies, the generated .runtimeconfig.json and .deps.json, and (with the right options) the runtime itself.

Terminal
# Read-only: run these on your machine, they need the dotnet CLI.
dotnet publish -c Release -o ./out

-c Release turns on optimizations and drops debug-only code paths. -o ./out chooses the output folder. The folder you copy is out/, not bin/.

Our in-browser runner compiles and runs a single main.cs. It has no dotnet CLI, so publish commands appear in bash blocks. The behavior of the resulting app (configuration, health, shutdown) is what the runnable examples show.

Framework-dependent or self-contained

This is the first real decision. It is about who provides the .NET runtime.

Framework-dependent (default) Self-contained
Runtime Must be installed on the server Copied next to your app
Size Small (hundreds of KB to a few MB) Large (about 70 MB or more, before trimming)
Patching Update the runtime once, all apps benefit You rebuild and redeploy to patch
Isolation Apps share one runtime Each app owns its runtime version
Command dotnet publish -c Release dotnet publish -c Release --self-contained -r linux-x64

-r is a runtime identifier (RID) such as linux-x64, linux-arm64, win-x64 or osx-arm64. A self-contained build is specific to one operating system and CPU architecture, because it contains native code.

XML
<!-- Read-only: the same choices written in the .csproj file. -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <RuntimeIdentifier>linux-x64</RuntimeIdentifier>
    <SelfContained>true</SelfContained>
  </PropertyGroup>
</Project>

A good default: framework-dependent when you control the server or use containers with Microsoft's runtime image, and self-contained when you ship to machines you do not control (a desktop tool, an appliance, a customer's server). The ASP.NET Core shared framework is a separate runtime component from the base .NET runtime, which is why a web app needs the ASP.NET Core runtime installed, not only the plain .NET one.

You can ask a running program which runtime it is using. This is useful in logs when you debug "it works on my machine":

C# Which runtime am I on?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first line prints .NET 10.0.13 here. On your server it prints whatever runtime is installed, which is exactly why logging it at startup is a good habit.

Trimming, single-file and ReadyToRun

Three options shrink or speed up the published output. They are independent switches, and each has trade-offs.

  • Single-file (-p:PublishSingleFile=true) bundles your assemblies into one executable. Deployment is one file to copy. Self-contained single-file apps extract nothing by default; native libraries can still be extracted at start.
  • ReadyToRun (-p:PublishReadyToRun=true) precompiles your IL to native code ahead of time, so the app starts faster because the JIT has less to do at launch. The output grows because it holds both IL and native code, and the JIT still re-optimizes hot methods later.
  • Trimming (-p:PublishTrimmed=true) removes code that static analysis shows is unused. It can shrink a self-contained app by more than half, but it breaks code that reaches things through reflection because the analyzer cannot see those uses.
Terminal
# Read-only: a typical "small and fast to start" self-contained publish.
dotnet publish -c Release -r linux-x64 --self-contained \
  -p:PublishSingleFile=true -p:PublishReadyToRun=true

Trimming and reflection do not mix without care. Libraries that look up types by name (serializers, DI containers using assembly scanning) may lose code at publish time and fail only at runtime. Use the trim warnings (IL2026, IL2067...) as a to-do list, and prefer source-generated alternatives such as the System.Text.Json source generator described in JSON.

Native AOT

Native AOT (ahead-of-time) compiles your whole app to a native executable with no JIT and no IL. Start-up is nearly instant, memory use is small, and no runtime needs to be installed. The price is a smaller world: no Assembly.LoadFrom, no Reflection.Emit, no dynamic code generation, and anything reflection-heavy must be rewritten or source-generated.

XML
<!-- Read-only: opt in with one property. -->
<PropertyGroup>
  <PublishAot>true</PublishAot>
</PropertyGroup>

ASP.NET Core supports Native AOT for Minimal APIs (using WebApplication.CreateSlimBuilder and source-generated JSON), but not for MVC or Razor views. It shines for serverless functions and small container services where cold start and memory cost real money. You can detect at runtime whether dynamic code is possible:

C# Is dynamic code supported?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

On a normal runtime both flags are True and the generated method works. In a Native AOT app IsDynamicCodeSupported is False, and the same code would throw PlatformNotSupportedException. Libraries use this flag to pick a slower but AOT-safe path.

Docker images

Containers are the most common way to run .NET services. A multi-stage Dockerfile builds with the big SDK image and copies only the published output into the small runtime image:

TEXT
# Read-only: a Dockerfile. Needs Docker; not runnable here.
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY *.csproj ./
RUN dotnet restore
COPY . ./
RUN dotnet publish -c Release -o /app --no-restore

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

Several details here are worth knowing:

  • Copying the .csproj and restoring before copying the rest of the source lets Docker cache the slow restore layer until your dependencies change.
  • Official .NET images listen on port 8080 (not 80) and run as a non-root user, which is why USER $APP_UID is available. Never run a web app as root in a container.
  • ASPNETCORE_HTTP_PORTS sets which port Kestrel binds. Platforms such as Kubernetes then map it.
  • Use dotnet publish container support instead if you prefer no Dockerfile: dotnet publish -t:PublishContainer builds an image from the SDK directly.

Environments

ASP.NET Core has a built-in idea of environment, a name like Development, Staging or Production. It comes from the ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT) variable and defaults to Production when absent. That default is deliberate: a forgotten variable should give the safe behavior.

The environment decides what is turned on. Development shows detailed exception pages; Production must not leak stack traces to visitors. You choose with app.Environment.IsDevelopment() or the other Is... helpers.

C# Production hides exception details

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Development prints the exception message (and the page contains the secret), Production returns a generic message with a reference you can look up in your logs. The status code is 500 in both. Never decide "is this safe to show?" per endpoint; decide once, in the pipeline, by environment.

Configuration in production

Configuration is layered: each source overrides the ones before it. The default order for WebApplication.CreateBuilder is:

  1. appsettings.json
  2. appsettings.{Environment}.json
  3. User secrets (Development only)
  4. Environment variables
  5. Command-line arguments

For production, the rule is simple: the code and the image are the same everywhere; configuration changes per environment and arrives from outside. Put non-secret defaults in appsettings.json, and let the platform inject connection strings and keys as environment variables (a double underscore __ stands for the : section separator). You met the full mechanism in Configuration and Options.

C# Environment variables override files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The host and the feature flag come from the environment, the port falls through from the file layer. Remember that environment variable names become part of your deployment contract: renaming a configuration key is a breaking change for the people who operate the app.

Never put real secrets in appsettings.json or in the image. Inject them at runtime (platform secret stores, a vault, or environment variables from one), and keep appsettings.json free of anything you would not paste in a public issue.

Health checks

An orchestrator (Kubernetes, a load balancer, Azure App Service) needs to ask your app one question: are you OK? ASP.NET Core ships health checks for that. You register checks and map an endpoint:

C# A health endpoint with a custom check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The readiness endpoint answers 503 Unhealthy while the warm-up has not finished, then 200 Healthy. Two endpoints are the standard split:

  • Liveness says "the process is not stuck". If it fails, the platform restarts the app. Keep it trivial and never check a database here, or a database outage will make your platform restart healthy apps in a loop.
  • Readiness says "I can take traffic now". If it fails, the platform stops sending requests but leaves the app running. Check dependencies here.

Graceful shutdown

Deployments replace running apps. The platform sends a termination signal (SIGTERM), waits a grace period (30 seconds on Kubernetes by default), then kills the process. A well-behaved app uses that time to stop accepting new requests and finish in-flight ones. ASP.NET Core does this when the host is told to stop: Kestrel stops listening and waits for active requests up to HostOptions.ShutdownTimeout, which is 30 seconds by default.

You can hook into the stages through IHostApplicationLifetime:

C# Observing the shutdown stages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The slow request completes even though shutdown began while it was running. Real apps use ApplicationStopping to flip a readiness flag (so the load balancer stops routing), ApplicationStopped to flush telemetry, and long-running work should accept a CancellationToken so it can end early; see Cancellation.

A frequent production bug: a hosting setup where docker stop takes exactly 10 seconds and then kills the container. That usually means the process never received SIGTERM (for example because a shell script wrapper is PID 1 and does not forward signals). Use the exec form ENTRYPOINT ["dotnet", "MyApp.dll"] as shown above, not a shell string.

A deployment checklist

Before the first real deployment, walk through this list:

  1. Publish in Release mode and run the published output locally (./out/MyApp) at least once, not only dotnet run.
  2. Log the runtime version, environment name and app version at startup.
  3. Confirm ASPNETCORE_ENVIRONMENT=Production on the server, and no developer exception page.
  4. Provide secrets from the platform, never from the repository or image.
  5. Add /healthz/live and /healthz/ready and point the platform probes at them.
  6. Put the app behind a reverse proxy or load balancer that terminates TLS, and configure forwarded headers (UseForwardedHeaders) so the app sees the original client address and scheme.
  7. Test a rolling restart: requests in flight must finish, and no request should fail.
  8. Decide how you roll back: keep the previous image or folder.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which publish style requires the .NET runtime to be installed on the server?

    A framework-dependent app contains only your code and relies on the runtime installed on the machine. Self-contained and Native AOT builds carry what they need with them.
  2. 2. What is the main limitation of Native AOT compared to a normal JIT-based publish?

    Native AOT compiles everything ahead of time and has no JIT, so dynamic code generation and reflection that the trimmer cannot see are unavailable. Configuration, async and Linux are all fine.
  3. 3. A liveness probe checks the database and the database goes down. What is the likely result?

    A failed liveness probe means 'restart me'. Restarting healthy app instances does not repair the database and can make an outage worse. Dependency checks belong in the readiness probe.
  4. 4. What is the environment name when ASPNETCORE_ENVIRONMENT is not set?

    The default is Production, on purpose: forgetting to set the variable should give the safe behavior (no developer exception page).
  5. 5. Which Dockerfile layout makes rebuilds fast when only your source code changed?

    Docker caches layers. If the project file did not change, the slow restore layer is reused and only the later layers are rebuilt.

Summary

  • dotnet publish -c Release produces the folder to deploy; dotnet build output is for development.
  • Framework-dependent output is small and relies on an installed runtime; self-contained output carries the runtime and targets one runtime identifier.
  • Single-file, ReadyToRun and trimming are separate switches; trimming and Native AOT restrict reflection and dynamic code.
  • Multi-stage Docker builds, port 8080 and a non-root user are the .NET container defaults.
  • The environment defaults to Production; configuration is layered, and secrets come from the platform at runtime.
  • Use separate liveness and readiness endpoints, and handle ApplicationStopping for graceful shutdown.

Next: Data Access in .NET