Part 5 · Chapter 18

.NET Services Deployment

From dotnet run to Kestrel, Nginx, systemd, Docker, and Azure App Service — deploying the Microsoft stack on any platform.

What you'll learn in this chapter

  • The three .NET deployment models: framework-dependent, self-contained, single file
  • Publishing and running ASP.NET Core apps with Kestrel
  • Nginx as a reverse proxy for .NET on Linux
  • Running as a systemd service on Linux servers
  • Multi-stage Docker builds for .NET
  • Azure App Service — the simplest .NET deployment
  • IIS on Windows Server
  • Health checks and environment-based configuration

The Swiss Army Knife

.NET (pronounced "dot net") is Microsoft's platform for building anything: web APIs, desktop apps, mobile apps, games (Unity uses it), IoT devices, and ML workloads. ASP.NET Core is the web framework — and it is, perhaps surprisingly, fully cross-platform. It runs on Linux, macOS, and Windows.

The built-in web server, Kestrel, is embedded directly into your app. You no longer need IIS to run .NET — though you might still use IIS on Windows as a reverse proxy. On Linux, Nginx takes that role.

🔧 The Swiss Army Knife Analogy

A Swiss Army knife has one handle but many tools: blade, scissors, screwdriver. .NET is similar — one runtime, but you build anything: web APIs (ASP.NET Core), console tools, background services, desktop GUIs. The deployment process is the same regardless of which tool you picked.

The Three Deployment Models

When you publish a .NET app, you choose one of three models:

ModelWhat it meansArtifact sizeRuntime required on server
Framework-dependentApp + your code only; .NET runtime must be installed on the serverSmall (~5 MB)Yes — install .NET on server
Self-containedApp + .NET runtime bundled togetherLarge (~70 MB)No — runtime is inside the publish folder
Single fileSelf-contained but compressed into one executableMedium (~50 MB)No
# Framework-dependent (smaller artifact)
dotnet publish -c Release -o ./publish

# Self-contained for Linux x64
dotnet publish -c Release -r linux-x64 --self-contained true -o ./publish

# Single-file self-contained
dotnet publish -c Release -r linux-x64 --self-contained true \
  -p:PublishSingleFile=true -o ./publish

# Run the app
dotnet ./publish/MyApp.dll        # framework-dependent
./publish/MyApp                   # self-contained executable

Kestrel + Nginx in Production

Kestrel is blazing fast, but it's not designed to face the public internet directly. Use Nginx in front — it handles SSL termination, compression, rate limiting, and static file serving, and passes dynamic requests to Kestrel.

appsettings.Production.json

{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://localhost:5000"
      }
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=mydb;User Id=myapp;Password=${DB_PASSWORD};"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

Nginx config

server {
    listen 80;
    server_name api.myapp.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name api.myapp.com;

    ssl_certificate /etc/letsencrypt/live/api.myapp.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.myapp.com/privkey.pem;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        client_max_body_size 10m;
    }
}

systemd Service on Linux

# /etc/systemd/system/myapp.service
[Unit]
Description=My ASP.NET Core Application
After=network.target

[Service]
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/dotnet /var/www/myapp/MyApp.dll
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=myapp
User=www-data
EnvironmentFile=/etc/myapp/app.env
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://localhost:5000

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp
sudo journalctl -u myapp -f

Environment Variables in .NET

.NET maps environment variables to appsettings.json keys using double underscore (__) as a path separator:

# These env vars override appsettings.json at runtime
ASPNETCORE_ENVIRONMENT=Production
ConnectionStrings__DefaultConnection=Server=localhost;Database=mydb;...
Jwt__SecretKey=super-secret-signing-key
Logging__LogLevel__Default=Warning
💡 Never Put Secrets in appsettings.json

appsettings.json is committed to Git. Use environment variables, Azure Key Vault, AWS Secrets Manager, or HashiCorp Vault for anything sensitive. The EnvironmentFile in your systemd service is the right place for server-level secrets.

Dockerfile for .NET — Multi-Stage Build

# Stage 1: Build
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS builder
WORKDIR /app

# Restore dependencies first (cached layer)
COPY *.csproj ./
RUN dotnet restore

# Build and publish
COPY . .
RUN dotnet publish -c Release -o /app/publish

# Stage 2: Runtime (smaller ASP.NET runtime image)
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runner
WORKDIR /app

COPY --from=builder /app/publish .

EXPOSE 5000

ENV ASPNETCORE_URLS=http://+:5000
ENV ASPNETCORE_ENVIRONMENT=Production

ENTRYPOINT ["dotnet", "MyApp.dll"]

Azure App Service — The Simplest .NET Deployment

For teams already in Azure, App Service is purpose-built for .NET. Microsoft manages the server, runtime, SSL, scaling, and deployment pipeline. You just ship your code.

# Create App Service plan and web app
az appservice plan create \
  --name my-plan \
  --resource-group my-rg \
  --sku B2 \
  --is-linux

az webapp create \
  --resource-group my-rg \
  --plan my-plan \
  --name my-dotnet-app \
  --runtime "DOTNETCORE:8.0"

# Set environment variables
az webapp config appsettings set \
  --resource-group my-rg \
  --name my-dotnet-app \
  --settings \
    ASPNETCORE_ENVIRONMENT=Production \
    DB_PASSWORD="@Microsoft.KeyVault(...)"

# Deploy via zip
dotnet publish -c Release -o ./publish
cd publish && zip -r ../deploy.zip .
az webapp deployment source config-zip \
  --resource-group my-rg \
  --name my-dotnet-app \
  --src ../deploy.zip

GitHub Actions to Azure App Service

- name: Build and publish
  run: dotnet publish -c Release -o publish

- name: Deploy to Azure App Service
  uses: azure/webapps-deploy@v3
  with:
    app-name: my-dotnet-app
    publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
    package: ./publish

IIS on Windows Server

For organisations running Windows Server, IIS remains the standard reverse proxy. The key difference from the old ASP.NET days: IIS no longer runs your .NET code — it proxies to Kestrel via the ASP.NET Core Module v2.

  1. Install the .NET 8 Hosting Bundle on Windows Server (includes the ASP.NET Core Module)
  2. Publish your app to a folder (e.g. C:\inetpub\wwwroot\myapp)
  3. In IIS Manager: create a new Site pointing to that folder
  4. Set the Application Pool's Managed Pipeline Mode to "No Managed Code" — Kestrel owns .NET now
  5. IIS forwards requests to Kestrel; Kestrel processes them and returns responses
🎉 Fun Fact

ASP.NET Core was a complete rewrite from the ground up, released in 2016. Microsoft specifically built it to be Linux-compatible — a radical move for a company historically synonymous with Windows. Today, many .NET services run on Ubuntu servers in AWS, with no Windows in sight.

Health Checks in .NET

// Program.cs
builder.Services.AddHealthChecks()
    .AddDbContextCheck<AppDbContext>()           // checks DB
    .AddDiskStorageHealthCheck(s => s.AddDrive("/", 1024))   // checks disk
    .AddUrlGroup(new Uri("https://api.stripe.com/v1"), "stripe");

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

Chapter Summary

  • Three deployment models: framework-dependent (small), self-contained (portable), single file (one executable)
  • Kestrel is the embedded web server — always put Nginx or IIS in front of it in production
  • Run as a systemd service on Linux with ASPNETCORE_ENVIRONMENT=Production
  • Use double-underscore (__) environment variables to override appsettings.json
  • Multi-stage Docker builds: SDK image for building, ASP.NET runtime image for running
  • Azure App Service is the most frictionless deployment target for ASP.NET Core
  • On Windows Server, IIS proxies to Kestrel via the ASP.NET Core Module