Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 52 ยท Testing, Performance and Deployment

Deployment: Kestrel, Reverse Proxies and Containers

Ship an ASP.NET Core app: configure Kestrel, trust a reverse proxy with forwarded headers, choose publish options and build a small Docker image.

An app that works with dotnet run is only half done. Production adds a different set of questions: which address does it listen on, who terminates TLS, what does the app see when a proxy sits in front of it, how do you package it, and how does the platform know it is healthy? ASP.NET Core answers each of these with a small piece of configuration, and none of them require changing your endpoints.

This lesson walks from the inside out: Kestrel, then the reverse proxy in front of it, then dotnet publish, then a container image. Some pieces run live here (Kestrel limits and forwarded headers, because they are plain library code); the tooling, nginx and Docker parts are read-only because they need a real machine.

The deployment picture

Almost every production setup looks like this. The internet talks to a reverse proxy (nginx, IIS, a cloud load balancer, Cloudflare). The proxy terminates TLS, filters traffic and forwards plain HTTP to Kestrel on a private port.

flowchart LR
    C["Browser"] -->|"HTTPS :443"| P["Reverse proxy<br/>nginx / IIS / load balancer"]
    P -->|"HTTP :8080<br/>X-Forwarded-* headers"| K["Kestrel<br/>your ASP.NET Core app"]
    K --> D[("Database")]
    O["Orchestrator<br/>Docker / Kubernetes"] -.->|"GET /health"| K

A reverse proxy handles TLS and public traffic; Kestrel serves the app on a private port; the platform probes a health endpoint.

Kestrel is a fast, production-ready server and can face the internet directly. A proxy is still common because it gives you one place for TLS certificates, caching, request buffering, several apps on one machine and protection against slow-client attacks.

Configuring Kestrel

Kestrel needs to know where to listen and how much to tolerate. Addresses normally come from configuration, not code. The standard ways are the ASPNETCORE_URLS environment variable, the --urls command-line argument, or the Kestrel:Endpoints section of appsettings.json:

JSON
{
  "Kestrel": {
    "Endpoints": {
      "Http": { "Url": "http://0.0.0.0:8080" }
    },
    "Limits": {
      "MaxRequestBodySize": 5242880
    }
  }
}

Limits can also be set in code with builder.WebHost.ConfigureKestrel. The most important ones are the maximum request body size (30 MB by default), the header timeout, the keep-alive timeout and the number of concurrent connections. Limits are a security feature: they stop one client from tying up memory or sockets.

C# Kestrel limits protect the server

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.

Bodies at or under the limit succeed; anything larger is rejected with 413 Payload Too Large before your handler can process it. The same idea applies to header sizes and timeouts. You can also override the limit per endpoint ([RequestSizeLimit] or the IHttpMaxRequestBodySizeFeature) when one route, such as an upload, needs more.

HTTPS and certificates

In production the certificate usually lives on the proxy, and Kestrel speaks plain HTTP on a private network. If Kestrel must terminate TLS itself, configure an endpoint with a certificate (Certificate:Path in configuration, or ListenAnyIP(443, o => o.UseHttps(...))). For development, dotnet dev-certs https --trust creates a local certificate. Never commit a certificate or its password; load them from a secret store (see Environments and Secrets).

Behind a reverse proxy: forwarded headers

When a proxy sits in front, Kestrel sees a request from the proxy. The remote IP is the proxy's address, and the scheme is http even though the browser used https. That breaks things: redirects to http://, links generated with the wrong scheme, rate limiting that sees one IP for everybody, audit logs that record the proxy.

Proxies pass the original values in headers: X-Forwarded-For (client IP), X-Forwarded-Proto (original scheme) and X-Forwarded-Host. The forwarded headers middleware reads them and rewrites Request.Scheme, Request.Host and Connection.RemoteIpAddress. It must be one of the first middleware in the pipeline.

C# Trusting X-Forwarded headers

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.

Without the middleware the app believes the request came over http from 127.0.0.1. With it, the app sees https and the real client address.

Never trust forwarded headers from just anyone. Any client can send X-Forwarded-For: 1.2.3.4 and pretend to be somebody else. The middleware therefore only honors headers from known proxies (KnownProxies and KnownNetworks), which by default means loopback only. In production, list your proxy's address or network explicitly, and make sure the proxy overwrites or appends the header instead of passing the client's value through blindly. Clearing the known lists to "make it work" opens a spoofing hole.

A minimal nginx server block for a Kestrel app on port 8080 looks like this (read-only):

NGINX
server {
    listen 443 ssl;
    server_name app.example.com;

    location / {
        proxy_pass         http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header   Host              $host;
        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   Upgrade           $http_upgrade;     # WebSockets
        proxy_set_header   Connection        $connection_upgrade;
    }
}

On Windows, IIS hosts the app in one of two ways. In-process hosting (the default) loads your app into the IIS worker process through the ASP.NET Core Module and uses IIS's own HTTP server; it is fastest. Out-of-process hosting runs Kestrel as a separate process and has IIS proxy to it. Either way, IIS sets the forwarded information for you through the module.

Publishing the app

dotnet run compiles in Debug mode and is for development. To deploy, run dotnet publish, which produces a folder of compiled files you can copy to a server (read-only commands):

Terminal
dotnet publish -c Release -o ./publish
dotnet ./publish/MyApp.dll

The main choices:

Option Meaning Trade-off
Framework-dependent (default) Needs the ASP.NET Core runtime installed on the machine Small output; the host patches the runtime
--self-contained Bundles the runtime with the app Larger output (tens of MB); no runtime install needed
-p:PublishSingleFile=true One executable instead of many files Easier to copy; slower first start unless compressed
-p:PublishTrimmed=true Removes unused framework code Smaller; can break reflection-heavy code
-p:PublishAot=true Native AOT: compiles to machine code Fast startup, tiny memory; many libraries are incompatible
-r linux-x64 Targets one operating system and CPU Required for self-contained, AOT and single file

Framework-dependent is the right default for servers you manage, and it is what container images do too, because the base image already contains the runtime. Self-contained shines when you cannot install anything on the target. Native AOT is excellent for small services and serverless functions; see Performance Tuning for its limits.

Two publish-time habits matter: build with -c Release so the compiler optimizes, and never ship the appsettings.Development.json secrets. Environment-specific values belong in environment variables on the server.

A Dockerfile for ASP.NET Core

Containers make deployment repeatable. The standard recipe is a multi-stage build: compile with the large SDK image, then copy only the published output into the small runtime image. Read-only:

DOCKERFILE
# Stage 1: build with the SDK
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY MyApp.csproj .
RUN dotnet restore                 # cached until the csproj changes
COPY . .
RUN dotnet publish -c Release -o /app --no-restore

# Stage 2: run on the small ASP.NET runtime image
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
COPY --from=build /app .
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
USER $APP_UID                       # run as the non-root user in the image
ENTRYPOINT ["dotnet", "MyApp.dll"]

Copying the .csproj and restoring before copying the source means Docker reuses the cached restore layer when only code changed, which makes rebuilds much faster. Since .NET 8 the official images listen on port 8080 and include a non-root user, so running unprivileged is one line. Add a .dockerignore listing bin/, obj/ and .git/ so the build context stays small.

Health in production

Platforms need to ask your app "are you alive?" and "can you take traffic?". Kubernetes calls these liveness and readiness probes; Docker has HEALTHCHECK; load balancers have target health checks. In ASP.NET Core you expose them with the health checks feature (AddHealthChecks, MapHealthChecks("/health")), covered in Rate Limiting, Health Checks and Resilience of the App. Keep the liveness check trivial, and put dependency checks (database, cache) in readiness so that a database outage drains traffic instead of restarting every pod.

Finally, plan for graceful shutdown. When the orchestrator sends SIGTERM, the host stops accepting new requests and gives in-flight ones a chance to finish (30 seconds by default, configurable with HostOptions.ShutdownTimeout). Make sure your orchestrator's grace period is at least as long, and your background services honor their cancellation tokens.

Production checklist

  • Listen on a configured address, not a hard-coded one.
  • Put a reverse proxy in front, and enable forwarded headers with explicit known proxies.
  • Set ASPNETCORE_ENVIRONMENT=Production so the developer exception page stays off.
  • Keep secrets in environment variables or a secret store, never in the image.
  • Build with -c Release, run as non-root, and expose a health endpoint.
  • Log to stdout in a structured format and collect it centrally (see Observability in Production).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A proxy terminates HTTPS and forwards plain HTTP to Kestrel. Without extra configuration, what does Request.Scheme report?

    Kestrel only sees the connection from the proxy. The forwarded headers middleware reads X-Forwarded-Proto and rewrites the scheme.
  2. 2. Why does the forwarded headers middleware ignore headers from unknown senders by default?

    Only listed proxies (KnownProxies and KnownNetworks, loopback by default) are trusted, otherwise IP-based logic such as rate limiting could be bypassed.
  3. 3. What is the main benefit of a multi-stage Dockerfile?

    The SDK image compiles the code; the final stage copies the output onto the much smaller aspnet runtime image.
  4. 4. Which publish option bundles the .NET runtime with your app?

    Self-contained output includes the runtime, so the target machine needs no installation. Trimming and single file are separate options.
  5. 5. A request body is larger than MaxRequestBodySize. What does Kestrel do?

    Kestrel enforces the limit while the body is read and answers 413 before the handler can process the oversized request.

Summary

  • A typical deployment is: client, reverse proxy (TLS), Kestrel on a private port, with health probes from the platform.
  • Configure Kestrel addresses and limits through configuration or ConfigureKestrel; limits protect against oversized or slow requests.
  • Behind a proxy, enable UseForwardedHeaders early and trust only known proxies, or the scheme and client IP will be wrong (or forgeable).
  • dotnet publish -c Release creates the deployable output; choose framework-dependent, self-contained, single file, trimmed or Native AOT by trade-off.
  • Build containers with a multi-stage Dockerfile, restore before copying sources for caching, and run as non-root.
  • Expose health endpoints, shut down gracefully and keep secrets out of images.

Next: Observability in Production