Publish and hosting
Publishing turns your ASP.NET Core project into a deployable folder or file, and hosting is how it runs in production: behind IIS on Windows or Nginx + systemd on Linux. Picking the right publish mode and configuring forwarded headers are the two places most deployments go wrong.
69.1 Why is it used?
- In the demo a Release publish for linux-x64 builds fine, but on the server it prints "You must install .NET" and ".NET location: Not found".
- Default dotnet publish is framework-dependent: only your code, the runtime must already be on the server.
- Two options: install the runtime on the server, or ship the runtime with the app.
# Publish for a Linux serverdotnet publish -c Release -r linux-x64 \ -o out/fdd-linux # Copy the folder to the server, run itcd out/fdd-linux./Shop$ dotnet publish -c Release -r linux-x64 \ -o out/fdd-linux Shop -> D:\SkillUp\tmp-C69\out\fdd-linux\$ ./ShopYou must install .NET to run this application. App: /app/fdd-linux/ShopArchitecture: x64App host version: 10.0.14.NET location: Not found69.2 Framework-dependent vs self-contained
- --self-contained copies the .NET runtime into the output.
- A runtime identifier (linux-x64, win-x64) is required, because the runtime differs per OS.
- Self-contained starts even on a server without the runtime.
# Framework-dependent (default)dotnet publish -c Release -r linux-x64 \ -o out/fdd-linux # Self-contained: runtime includeddotnet publish -c Release -r linux-x64 \ --self-contained -o out/sc-linux$ du -sh out/fdd-linux out/sc-linux121K out/fdd-linux106M out/sc-linux$ ls out/sc-linux | wc -l336$ cd out/sc-linux$ ASPNETCORE_HTTP_PORTS=5069 ./Shopinfo: Microsoft.Hosting.Lifetime[14] Now listening on: http://[::]:5069info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.69.3 Single-file, trimming and Native AOT
- PublishSingleFile packs the 336 files into one executable.
- PublishTrimmed removes unused runtime code; code that uses reflection can get trimmed away.
- Native AOT compiles to machine code at publish time: no JIT, very fast startup.
- AOT needs the platform linker (Visual Studio C++ build tools on Windows) and cannot cross-compile between OSes; for Linux the demo used the sdk:10.0-noble-aot image in docker.
# Single-file: one executabledotnet publish -c Release -r linux-x64 \ --self-contained \ -p:PublishSingleFile=true -o out/single # Trimming: unused code removedotnet publish -c Release -r linux-x64 \ --self-contained \ -p:PublishSingleFile=true \ -p:PublishTrimmed=true -o out/trimmed$ dotnet publish ... -p:PublishTrimmed=true Optimizing assemblies for size. This process might take a while. Shop -> D:\SkillUp\tmp-C69\out\trimmed\$ ls -lh out/single/Shop out/trimmed/Shop97M out/single/Shop22M out/trimmed/Shop# Native AOT on Windowsdotnet publish -c Release -r win-x64 \ /p:PublishAot=true # Linux AOT: SDK image in dockerdocker run --rm -v ${PWD}:/src -w /src \ mcr.microsoft.com/dotnet/sdk:10.0-noble-aot \ dotnet publish -c Release -r linux-x64 \ /p:PublishAot=true -o out/aot$ dotnet publish -c Release -r win-x64 /p:PublishAot=trueerror : Platform linker not found. Ensure you have all therequired prerequisites documented athttps://aka.ms/nativeaot-prerequisites, in particular theDesktop Development for C++ workload in Visual Studio.$ docker run ... sdk:10.0-noble-aot dotnet publish ... Generating native code Shop -> /src/out/aot/$ ls -lh out/aot/Shop16M out/aot/Shop| Publish option | Flag | Size in the demo | Note |
|---|---|---|---|
| Framework-dependent (default) | -r linux-x64 | 121K | Needs the runtime on the server |
| Self-contained | --self-contained | 106M, 336 files | Runtime included; RID required |
| Single-file | -p:PublishSingleFile=true | 97M | One executable |
| Trimmed | -p:PublishTrimmed=true | 22M | Removes unused code; reflection can break, never ignore trim warnings |
| Native AOT | /p:PublishAot=true | 16M | Machine code, no JIT, fast startup; build on target OS; MVC controllers not supported |
- Step 1
1.Does the server have the .NET runtime installed?
- Step 2
2.Yes: framework-dependent publish (121 KB here)
- Step 3
3.No: --self-contained with a runtime identifier (106 MB, 336 files)
- Step 4
4.Want one file? add PublishSingleFile (97 MB), then PublishTrimmed (22 MB) if there are zero trim warnings
- Step 5
5.Need very fast startup and small size? Native AOT (16 MB), built on the target OS
69.4 IIS on Windows
- A normal framework-dependent publish adds web.config automatically.
- AspNetCoreModuleV2 (ANCM) connects IIS to your app; processPath dotnet with Shop.dll as the argument.
- hostingModel="inprocess" runs the app inside the IIS worker process.
- The server needs the ASP.NET Core Hosting Bundle installed.
<configuration> <system.webServer> <handlers> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath="dotnet" arguments=".\Shop.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" /> </system.webServer></configuration>$ dotnet publish -c Release -o out/fdd$ ls out/fddShop.deps.json Shop.dll Shop.exe Shop.pdbShop.runtimeconfig.json appsettings.jsonappsettings.Development.json web.config69.5 Nginx reverse proxy on Linux
- Step 1
1.Client sends HTTPS to port 443
- Step 2
2.Nginx terminates TLS and adds X-Forwarded-For / X-Forwarded-Proto
- Step 3
3.Nginx proxy_pass to Kestrel on 127.0.0.1:5069
- Step 4
4.UseForwardedHeaders (first middleware) restores scheme https and the real client IP
- Step 5
5.Your app handles the request
- Step 6
6.systemd starts the app on boot and restarts it on crash
IIS on Windows: ASP.NET Core Module (web.config) instead of Nginx + systemd
- Nginx listens on 443 with the certificate and proxy_passes to 127.0.0.1:5069.
- It adds X-Forwarded-For and X-Forwarded-Proto headers.
- Without extra code the app still sees "http from 127.0.0.1": real scheme and client are lost.
server { listen 443 ssl; server_name shop.local; ssl_certificate /etc/nginx/certs/shop.crt; ssl_certificate_key /etc/nginx/certs/shop.key; location / { proxy_pass http://127.0.0.1:5069; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }}$ curl -k https://localhost:8443/whoamihttp from 127.0.0.169.6 UseForwardedHeaders and KnownProxies
- ASP.NET Core does not read forwarded headers by default.
- Configure ForwardedHeadersOptions with XForwardedFor | XForwardedProto and call UseForwardedHeaders first in the pipeline.
- Now whoami returns "https from" the real client IP.
- Checkpoint: with Nginx on another machine (10.69.0.5) you get "http from 10.69.0.5", because headers are accepted only from known proxies (default: localhost). This stops clients from faking their IP.
- Fix: KnownProxies.Add(10.69.0.5), or KnownIPNetworks for a subnet (KnownNetworks is obsolete in .NET 10).
using Microsoft.AspNetCore.HttpOverrides; var builder = WebApplication.CreateBuilder(args);builder.Services.Configure< ForwardedHeadersOptions>(o => o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);var app = builder.Build();app.UseForwardedHeaders(); app.MapGet("/whoami", (HttpContext ctx) => $"{ctx.Request.Scheme} from " + $"{ctx.Connection.RemoteIpAddress}");app.Run();$ curl -k https://localhost:8443/whoamihttps from 172.17.0.1 # nginx on another machine: 10.69.0.5, app: 10.69.0.10$ curl -k https://localhost:8443/whoamihttp from 10.69.0.5using System.Net;using Microsoft.AspNetCore.HttpOverrides;var builder = WebApplication.CreateBuilder(args);builder.Services.Configure< ForwardedHeadersOptions>(o =>{ o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; o.KnownProxies.Add( IPAddress.Parse("10.69.0.5"));});var app = builder.Build();app.UseForwardedHeaders();$ curl -k https://localhost:8443/whoamihttps from 10.69.0.169.7 systemd: run the app as a service
- ExecStart points to the self-contained executable.
- Restart=always restarts the app after a crash.
- Runs as www-data with ASPNETCORE_ENVIRONMENT=Production and ASPNETCORE_URLS on 127.0.0.1:5069.
- WantedBy=multi-user.target + systemctl enable starts it on every boot.
[Unit]Description=Shop API (ASP.NET Core)After=network.target [Service]WorkingDirectory=/var/www/shopExecStart=/var/www/shop/ShopRestart=alwaysUser=www-dataEnvironment=ASPNETCORE_ENVIRONMENT=ProductionEnvironment=ASPNETCORE_URLS=http://127.0.0.1:5069KillSignal=SIGINT [Install]WantedBy=multi-user.target69.8 Common mistakes
- Framework-dependent publish to a server without the runtime.
- UseHttpsRedirection before UseForwardedHeaders: infinite redirect loop behind Nginx.
- Forgetting KnownProxies when the proxy is on another machine: wrong scheme and IP.
- Ignoring trim/AOT warnings: reflection-based code breaks at runtime.
- Thinking Kestrel is only for development: it is production-ready and can face the internet; a reverse proxy just makes TLS, many apps on one port and load balancing easier.
// Wrong: redirect loopvar app = builder.Build();app.UseHttpsRedirection();app.UseForwardedHeaders();// curl -k -L https://localhost:8443/whoami// 307 Location: https://localhost:8443/whoami// curl: (47) Maximum (50) redirects followed // Right: forwarded headers firstvar app = builder.Build();app.UseForwardedHeaders();app.UseHttpsRedirection();// curl -k -L https://localhost:8443/whoami// 200 OK: https from 172.17.0.169.9 Interview tips
- dotnet publish -c Release: framework-dependent if the runtime is there, self-contained otherwise, Native AOT for fast startup.
- Linux: Kestrel on localhost, Nginx in front for TLS, systemd keeps it alive.
- UseForwardedHeaders first, with KnownProxies for a remote proxy.
- Windows: IIS runs the app through the ASP.NET Core Module (web.config, Hosting Bundle).
- AOT limits: no MVC controllers, build on the target OS, zero warnings.