---
title: "Deploy an ASP.NET Core app"
description: "Deploy ASP.NET Core to an exe.dev VM: .NET 10 LTS, Kestrel under systemd, git push deploys, EF Core and SQLite on a real disk, and exe.dev sign-in."
url: https://exe-staging.dev/deploy/aspnet-core
category: "Frameworks"
updated: 2026-11-16
---

# Deploy an ASP.NET Core app

> **For agents:** with your user's OK, this sets up ASP.NET Core on a new exe.dev VM in their account: `curl -fsSL https://exe-staging.dev/deploy/aspnet-core/prompt.txt | ssh exe.dev new --prompt=/dev/stdin` (or open https://exe-staging.dev/deploy/aspnet-core/new). Already on the VM? Skip this.

Your .NET web app on a Linux VM of its own. git push to deploy.

- **Software:** ASP.NET Core (https://dotnet.microsoft.com/apps/aspnet)
- **Source:** https://github.com/dotnet/aspnetcore
- **License:** MIT
- **Time:** 15 minutes
- **Example VM name:** `my-aspnet` (yours will differ; on the VM, `hostname` prints it)
- **Machine-readable:** https://exe-staging.dev/deploy/aspnet-core/manifest.json

## What you get

- The .NET 10 SDK installed from Ubuntu's packages, and the app published and running as app.service on 127.0.0.1:8000, enabled to come back after a reboot.
- A ~/app.git repository whose pre-receive hook publishes each push to main into a new release and rejects the push if the deploy fails.
- Settings and secrets in ~/app.env (mode 600), read by the build and by the service; ASP.NET Core sees them as configuration.
- Data in ~/data, backed up nightly by app-backup.timer, with the newest backup opened and checked in a scratch directory.
- With REPO=new, a Razor Pages guestbook on EF Core and SQLite that signs visitors in from exe.dev's X-ExeDev-Email header, makes the owner an admin, and trusts the proxy's forwarded headers.

Running on the VM:

- **Your ASP.NET Core app**: `dotnet publish` output, run by Kestrel as app.service under systemd, on 127.0.0.1, port 8000, data in `~/app → the current release in ~/releases`
- **.NET 10 (LTS)**: the SDK and ASP.NET Core runtime from Ubuntu's own packages, updated by apt
- **git push deploys**: a pre-receive hook in ~/app.git publishes, backs up, switches, and checks, data in `~/app.git`
- **SQLite**: EF Core with migrations in new apps; Data Protection keys beside it, data in `~/data`
- **Nightly backup**: app-backup.timer; data, settings, and the repository, data in `~/backups`

How it is reached:

- https://my-aspnet.exe.xyz/ (private): your app, signed in with exe.dev, until you make it public
- my-aspnet.exe.xyz:app.git (private): `git push exe main` deploys

## Deploy with Shelley

Open https://exe-staging.dev/deploy/aspnet-core/new to create a VM whose agent, Shelley, follows this recipe. From a terminal:

```sh
curl -fsSL https://exe-staging.dev/deploy/aspnet-core/prompt.txt | ssh exe.dev new --prompt=/dev/stdin
```

Or follow the steps below by hand.

ASP.NET Core runs well on Linux, and this page gives your app a Linux
machine of its own: .NET patched through Ubuntu's packages, Kestrel under
systemd, SQLite and keys on a real disk, and a fresh publish on every
`git push`. exe.dev serves it on HTTPS, behind its login until you decide
otherwise.

That login is what internal tools will like: exe.dev tells your app who
each visitor is in a header, and a short authentication handler turns it
into an ordinary `User`, so `[Authorize]` works with no passwords,
Identity tables, or login page. The VM is always on, Shelley on the VM
can debug it with you, and the app can call LLMs through exe.dev without
an API key. Bring a GitHub repository, or start from a small Razor Pages
app with EF Core and SQLite.

## Open your app

When setup finishes, open `https://my-aspnet.exe.xyz/` and sign in to
exe.dev if asked. A new app shows a guestbook that greets you by your
exe.dev email; you're its admin. Sign it: the message lands in SQLite at
`~/data/app.db` and survives redeploys and reboots.

## Deploy with git push

The VM deploys whatever you push to `main` in its `~/app.git`. **On your
computer**, clone the new app Shelley started, or add the VM as a remote
to your own checkout (GitHub stays your source of truth):

```bash
git clone -o exe my-aspnet.exe.xyz:app.git my-aspnet   # a new app
git remote add exe my-aspnet.exe.xyz:app.git            # or, in your repository
```

Then commit and push (your default branch, if it isn't `main`):

```bash
git push exe main
```

The build streams back and ends with `==> Deployed abc1234: HTTP 200 on
port 8000`. If `ssh` can't find the VM, use
`vm+my-aspnet@vm.exe.xyz:app.git` ([why](/docs/faq/ssh-destination)).
Locally, `dotnet run` uses its own `app.db` and you're signed out, since
no proxy adds the header; send it yourself to try signed-in pages:
`curl -H 'X-ExeDev-Email: you@example.com' http://localhost:<port>/`.

Each push publishes into a new directory in `~/releases`, backs up
`~/data`, switches `~/app` to it, and restarts `app.service`. If the
build fails or the new version doesn't answer within a minute, the old
one comes back and git rejects the push, so the VM's `main` is always
what's running. To roll back, push an older commit:
`git push -f exe <good-sha>:main`.

A deploy is a restart, not a zero-downtime switch: requests in flight
finish, then visitors get the proxy's error page for the second or two
the new version takes to start. That's fine for most internal tools and
small sites.

To deploy from GitHub instead, without pushing to the VM, run this on the
VM (or ask Shelley to, or put it in a systemd timer) once `~/app.git` is
a clone of your GitHub repository:

```bash
git -C ~/app.git fetch origin '+refs/heads/*:refs/heads/*' && ~/app.git/hooks/pre-receive HEAD
```

## Settings and secrets

Settings and secrets go in `~/app.env` on the VM as `KEY=value` lines
(single-quote values with spaces or `$`), not in `appsettings.json`,
which is in git. The build and the service both read the file, and the
nightly backup includes it. ASP.NET Core sees them as configuration that
overrides `appsettings.json`, with `__` for each `:`:
`ConnectionStrings__Default` is `GetConnectionString("Default")`, and
`Stripe__Key` is `Configuration["Stripe:Key"]`. After a change, run
`sudo systemctl restart app`. The app runs as `Production`. `PROJECT`
names the `.csproj` to publish if a repository has more than one web
project.

To keep an outside API's key off the VM entirely, an
[HTTP proxy integration](/docs/integrations-http-proxy) can add it to
each request at exe.dev ([how](/deploy/agent-secrets)).

## Your database

A new app uses EF Core with SQLite at `~/data/app.db` and applies its
migrations when it starts. To change the model, add a migration **on
your computer** (`dotnet-ef` is in the repository's tool manifest) and
push:

```bash
dotnet tool restore
dotnet ef migrations add AddLikes
git add . && git commit -m "Add likes" && git push exe main
```

The hook backs up `~/data` before each switch, but a rollback doesn't
undo a migration, so add columns rather than renaming them. A model
change without a migration stops the new version at startup, so the
deploy rolls back. If your app migrates some other way, set
`MIGRATE_COMMAND` in `~/app.env` (say, `'dotnet tool restore && dotnet
ef database update'`); the hook runs it in the new build before the
switch. Keep uploads and other files the app writes in `~/data` too.

Other databases run on the same VM; migrations are per provider, so
generate a fresh initial one:

- [PostgreSQL](/deploy/postgres#run-it-next-to-your-app): add
  `Npgsql.EntityFrameworkCore.PostgreSQL`, call `UseNpgsql`, and set
  `ConnectionStrings__Default='Host=localhost;Database=app;Username=app;Password=...'`.
- [MySQL](/deploy/mysql): `Pomelo.EntityFrameworkCore.MySql`, the same way.
- SQL Server: in Microsoft's container, which needs some care on
  exe.dev; see [Use SQL Server](#sql-server).

## Behind the proxy

exe.dev's [HTTPS proxy](/docs/proxy) ends TLS, redirects to HTTPS, sends
HSTS, and connects to Kestrel on port 8000 **from 127.0.0.1**, with the
visitor's scheme and address in `X-Forwarded-Proto` and
`X-Forwarded-For`. The new app's `Program.cs` has what an app needs for
that:

```csharp
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;

// Believe X-Forwarded-For and X-Forwarded-Proto from the proxy. Only
// loopback is trusted by default, and that's where the proxy connects from.
builder.Services.Configure<ForwardedHeadersOptions>(options =>
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);

// Keep the keys behind cookies and antiforgery tokens in ~/data, under a
// fixed name; by default the name comes from the release directory, so
// every deploy would sign everyone out.
builder.Services.AddDataProtection()
    .SetApplicationName("MyApp")
    .PersistKeysToFileSystem(new DirectoryInfo(builder.Configuration["DataProtectionKeys"] ?? "keys"));

var app = builder.Build();
app.UseForwardedHeaders();   // first, before anything that reads the scheme or IP
```

Without the forwarded headers, `Request.Scheme` is `http`, which breaks
absolute links, OAuth redirect URIs, and `Secure` cookies, and every
visitor's IP is 127.0.0.1. Drop the templates' `UseHttpsRedirection()`
and `UseHsts()`: exe.dev does both. Don't set
`ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` instead: it trusts the headers
from any address.

## Let exe.dev handle sign-in

For signed-in visitors, the proxy adds `X-ExeDev-Email` and
`X-ExeDev-UserID` to each request and strips any a visitor sends
([login with exe](/docs/login-with-exe)). On a private app, that's
everyone who gets in. The new app's `ExeDevAuthentication.cs`, a small
handler with no package dependencies (copy it into your own app), turns
the header into a normal user:

```csharp
builder.Services.AddAuthentication(ExeDevAuthentication.SchemeName)
    .AddScheme<AuthenticationSchemeOptions, ExeDevAuthentication>(ExeDevAuthentication.SchemeName, null);
builder.Services.AddAuthorization();
```

`User.Identity.Name` is the email. Emails in `AdminEmails` in `~/app.env`
(comma-separated; yours to start with) get the `admin` role. `[Authorize]`,
roles, and `.RequireAuthorization()` work as usual, and signed-out
visitors who need to sign in go to exe.dev's login and come back. An app
with ASP.NET Core Identity can keep it and add this scheme beside it.

This is safe **only because the proxy is the only way in**: the header is
plain text, and anything that reaches Kestrel directly can claim to be
anyone. That's why the service listens on 127.0.0.1. Don't change
`ASPNETCORE_URLS` to `0.0.0.0`: on a
[Tailscale](/docs/integrations-tailscale-wif) tailnet or any other
network that reaches the VM, others could skip exe.dev and forge the
header.

To let a colleague in, run
`ssh exe.dev share add my-aspnet colleague@example.com` **on your
computer**. They arrive signed in as themselves.

## Blazor and SignalR

Blazor Server, and interactive server rendering, keep a SignalR
connection to each browser over WebSockets, which exe.dev's proxy passes
through, private or public. `dotnet new blazor --interactivity Server`
deploys with this hook as it is. A deploy drops every circuit: browsers
show the reconnect banner, then reload into a fresh one, so keep state
that matters in the database. For sign-in, add
`builder.Services.AddCascadingAuthenticationState()`, and `<AuthorizeView>`
sees the exe.dev user.

## Call an LLM

exe.dev's [LLM integration](/docs/integrations-llm) answers at
`https://llm.int.exe.xyz` from your VM with no API key; usage is billed
to your exe.dev account. Use the
[OpenAI .NET library](https://github.com/openai/openai-dotnet) through
[Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/microsoft-extensions-ai),
so your code depends on `IChatClient`, not on one vendor:

```bash
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI
```

In `Program.cs`:

```csharp
using System.ClientModel;
using Microsoft.Extensions.AI;
using OpenAI;

builder.Services.AddChatClient(
    new OpenAIClient(
        new ApiKeyCredential(builder.Configuration["Llm:Key"] ?? "unused"),
        new OpenAIClientOptions { Endpoint = new Uri(builder.Configuration["Llm:Endpoint"] ?? "https://llm.int.exe.xyz/v1") })
    .GetChatClient(builder.Configuration["Llm:Model"] ?? "gpt-6-luna")
    .AsIChatClient());

// After builder.Build():
// Signed-in users only: every call spends your exe.dev LLM allocation.
app.MapPost("/ask", async (IChatClient llm, Question q) =>
    (await llm.GetResponseAsync(q.Text)).Text)
    .RequireAuthorization();

record Question(string Text);
```

Deploy, then try it on the VM, signed in as yourself:

```bash
curl -s http://127.0.0.1:8000/ask -H 'X-ExeDev-Email: you@example.com' \
  -H 'Content-Type: application/json' -d '{"text":"Say hi in three words"}'
```

`curl -s https://llm.int.exe.xyz/v1/models` on the VM lists the models;
set `Llm__Model` in `~/app.env` to switch. Claude is there too, through
Anthropic's Messages API at the same address. On your computer, point
`Llm__Endpoint` and `Llm__Key` at a provider.

## Make it public, add a domain

The app is private: only people you've [shared it with](/docs/sharing)
get in. **On your computer**, `ssh exe.dev share set-public my-aspnet`
opens it to everyone, and `set-private` closes it again. Public visitors
aren't signed in unless they choose to be, and `[Authorize]` pages send
them to exe.dev's login. For your own domain, point a CNAME at
`my-aspnet.exe.xyz` and run `ssh exe.dev domain add my-aspnet
app.example.com` ([custom domains](/docs/cnames)).

## Background jobs and backups

The VM doesn't sleep, so `BackgroundService`s, Hangfire, and Quartz.NET
run as long as the app does. For a job that shouldn't restart with each
deploy, copy `app-backup.service` and `.timer` under a new name and point
`ExecStart` at it (with `WorkingDirectory=/home/exedev/app` and
`EnvironmentFile=/home/exedev/app.env`).

Every night, and before each deploy, `~/bin/app-backup` saves `~/data`
(SQLite through `.backup`, and the Data Protection keys), `~/app.env`,
and the `~/app.git` repository to `~/backups`, keeping the 14 newest of
each kind. Run it yourself before anything risky. The archives hold your
secrets, so keep the copies you take off the VM private. **On your
computer**:

```bash
scp -r my-aspnet.exe.xyz:backups ./my-aspnet-backups
```

For staging, `ssh exe.dev cp my-aspnet my-aspnet-staging` copies the
whole VM ([dev, test, prod](/deploy/dev-test-prod)).

## Ask Shelley

Shelley, at `https://my-aspnet.shelley.exe.xyz/`, works on this VM with
you, with the .NET SDK right there to build and test. Try: "The last
deploy failed; tell me why", "Show me today's exceptions from journalctl
-u app", "Add an admin page only AdminEmails can open", or "Move my
database to PostgreSQL on this VM".

## The nuts and bolts

Happy with what Deploy set up? You can stop here. These are the setup
steps Shelley follows, which you can run by hand, and the commands for
later.

<details id="create-the-vm" data-manual-setup class="dp-details">
<summary>Set up by hand</summary>

### Create the VM

On your computer (pick another name if `my-aspnet` is taken):

```bash
ssh exe.dev new --name=my-aspnet
ssh my-aspnet.exe.xyz
```

Everything else runs **on the VM**, as `exedev`.

### Install .NET

.NET 10 is in Ubuntu 24.04's own package feed, which is Microsoft's
recommended way to install it there. Canonical builds it and ships its
monthly patches through `apt`. The SDK includes the ASP.NET Core runtime:

```bash
sudo apt-get update
sudo apt-get install -y dotnet-sdk-10.0
dotnet --list-sdks
dotnet --list-runtimes
```

Expect a `10.0.1xx` SDK and `Microsoft.AspNetCore.App 10.0.x`. The SDK
sends Microsoft usage telemetry unless told not to; the hook turns it
off for builds, and `echo 'export DOTNET_CLI_TELEMETRY_OPTOUT=1' >> ~/.bashrc`
does the same for your shell.

### Settings, data, and the service

Create the data and release directories and a private settings file.
This leaves an existing `~/app.env` alone:

```bash
mkdir -p ~/data ~/releases ~/backups
if [ ! -e ~/app.env ]; then
  install -m 600 /dev/null ~/app.env
  cat >> ~/app.env <<EOF
# Settings and secrets for the app: KEY=value, one per line. Quote values
# with spaces or \$ in 'single quotes'. Read by the build and by app.service.
# ASP.NET Core sees Section__Key as the configuration key Section:Key.
# After changing it: sudo systemctl restart app
# The web project the deploy hook publishes, if there's more than one:
PROJECT=
# Where Data Protection keeps its keys (cookies, antiforgery tokens):
DataProtectionKeys=/home/exedev/data/keys
# exe.dev users (comma-separated) who get the admin role:
AdminEmails=$(curl -fsS https://reflection.int.exe.xyz/email | jq -r .email)
EOF
fi
stat -c '%a %n' ~/app.env
grep AdminEmails ~/app.env
```

Expect `600 /home/exedev/app.env` and your exe.dev email. Now the
service. It runs the release that `~/app` points at, from inside it, so
ASP.NET Core finds `appsettings.json` and `wwwroot`. `bin/app` is a link
the hook makes to the app's own launcher. Kestrel listens on
127.0.0.1:8000, where exe.dev's proxy sends `https://my-aspnet.exe.xyz/`:

```bash
sudo tee /etc/systemd/system/app.service >/dev/null <<'EOF'
[Unit]
Description=ASP.NET Core app (~/app)
After=network-online.target
Wants=network-online.target

[Service]
User=exedev
WorkingDirectory=/home/exedev/app
# Loopback only: exe.dev's proxy connects from 127.0.0.1, and nothing else
# should reach Kestrel (it trusts the proxy's X-ExeDev-Email header).
Environment=ASPNETCORE_URLS=http://127.0.0.1:8000
Environment=DOTNET_NOLOGO=1
EnvironmentFile=/home/exedev/app.env
ExecStart=/home/exedev/app/bin/app
Restart=always
RestartSec=3
# systemctl stop/restart sends SIGTERM; Kestrel finishes requests in
# flight, then systemd sends SIGKILL after this long.
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable app.service
```

It starts with the first deploy.

### Back up every night

`~/bin/app-backup` saves everything that isn't in a release: `~/data`
(each SQLite database through `.backup`, which is safe while the app
writes, and then checked), `~/app.env`, and the repository in
`~/app.git` as a git bundle. A new app's only copy lives there until you
clone it. It keeps the 14 newest backups of each kind: `nightly`,
`deploy` (the hook takes one before each switch), and `manual`.

```bash
mkdir -p ~/bin
cat > ~/bin/app-backup <<'EOF'
#!/usr/bin/env bash
# Back up ~/data, ~/app.env and ~/app.git to ~/backups/app-<kind>-<time>.tar.gz.
# SQLite databases are copied with .backup, safe while the app runs, and
# checked. Keeps the 14 newest backups of each kind.
# Usage: app-backup [nightly|deploy|manual]
set -euo pipefail
umask 077
kind=${1:-manual}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$HOME/backups" "$work/data"
cd "$HOME/data"
rsync -a --exclude='*.db' --exclude='*.db-*' --exclude='*.sqlite*' ./ "$work/data/"
find . -type f \( -name '*.db' -o -name '*.sqlite' -o -name '*.sqlite3' \) | while read -r db; do
  mkdir -p "$work/data/$(dirname "$db")"
  sqlite3 "$db" ".backup '$work/data/$db'"
  [ "$(sqlite3 "$work/data/$db" 'PRAGMA quick_check')" = ok ]
done
cp "$HOME/app.env" "$work/"
if git -C "$HOME/app.git" rev-parse -q --verify HEAD >/dev/null; then
  git -C "$HOME/app.git" bundle create -q "$work/app.bundle" --all
fi
out="$HOME/backups/app-$kind-$(date -u +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$out.part" -C "$work" .
mv "$out.part" "$out"
ls -1t "$HOME/backups/app-$kind-"*.tar.gz | tail -n +15 | xargs -r rm --
echo "$out"
EOF
chmod +x ~/bin/app-backup
```

Run it every night with a systemd timer:

```bash
sudo tee /etc/systemd/system/app-backup.service >/dev/null <<'EOF'
[Unit]
Description=Back up the app's data, settings and repository to ~/backups

[Service]
Type=oneshot
User=exedev
ExecStart=/home/exedev/bin/app-backup nightly
EOF
sudo tee /etc/systemd/system/app-backup.timer >/dev/null <<'EOF'
[Unit]
Description=Back up the app every night

[Timer]
OnCalendar=*-*-* 03:00:00 UTC
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now app-backup.timer
systemctl list-timers app-backup.timer
```

Expect the next run, tonight. You'll take the first backup once the app
is deployed.

### Get the code

The VM deploys from a bare git repository, `~/app.git`. Create it one of
two ways.

**Start a new app** (`REPO=new`): an empty repository whose branch is
`main`.

```bash
git init --bare -b main ~/app.git
```

**Bring your GitHub repository**: a copy of it. A public repository
clones directly; replace `OWNER/NAME`:

```bash
git clone --bare https://github.com/OWNER/NAME.git ~/app.git
git -C ~/app.git symbolic-ref --short HEAD
```

The last line prints the branch that will deploy: your default branch.

For a **private** repository, connect GitHub to exe.dev once (on the
[Integrations page](https://exe.dev/integrations)) and attach the
repository to this VM. On your computer:

```bash
ssh exe.dev integrations add github --name aspnet-repo --repository OWNER/NAME --readonly --attach vm:my-aspnet
```

Then clone through the integration on the VM. No token lands on the disk
([GitHub integration](/docs/integrations-github)):

```bash
git clone --bare https://github.int.exe.xyz/OWNER/NAME.git ~/app.git
```

If that clone fails with "not found" or a 403, the integration isn't
attached to this VM yet.

### Add the deploy hook

Git runs `hooks/pre-receive` before it accepts a push. This one publishes
the pushed commit into its own directory under `~/releases`, backs up
`~/data`, switches `~/app` to it, restarts the service, and checks that
it answers. If any step fails, it switches back and rejects the push, so
`main` on the VM is always what's running.

```bash
cat > ~/app.git/hooks/pre-receive <<'EOF'
#!/usr/bin/env bash
# Deploys the app. Git runs this before accepting a push to ~/app.git;
# if the deploy fails, the push is rejected and the running version stays.
# To redeploy main by hand:  ~/app.git/hooks/pre-receive HEAD
set -euo pipefail
export GIT_DIR=$HOME/app.git
branch=$(git symbolic-ref --short HEAD)  # the branch that deploys
rev=
if [ $# -gt 0 ]; then
  rev=$(git rev-parse --verify "$1^{commit}")
else
  while read -r _ new ref; do
    [ "$ref" = "refs/heads/$branch" ] || continue
    case $new in
      *[!0]*) rev=$new ;;
      *) echo "==> Refusing to delete $branch: it's what deploys."; exit 1 ;;
    esac
  done
  [ -n "$rev" ] || exit 0  # other branches are kept, not deployed
fi

exec 9>"$HOME/.deploy.lock" && flock 9  # one deploy at a time
release=$HOME/releases/$(date -u +%Y%m%d-%H%M%S)-${rev:0:7}
src=$(mktemp -d)
previous=$(readlink "$HOME/app" || true)
fail() {  # put the previous release back and reject the push
  trap - ERR
  echo "==> Deploy FAILED${1:+: $1}. Still running: ${previous:-nothing}"
  if [ -n "$previous" ] && [ "$(readlink "$HOME/app")" != "$previous" ]; then
    ln -sfn "$previous" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app"
    sudo systemctl restart app
  fi
  rm -rf "$release" "$src"
  exit 1
}
trap fail ERR

echo "==> Building ${rev:0:7}"
git archive "$rev" | tar -x -C "$src"
unset GIT_DIR GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_QUARANTINE_PATH
cd "$src"
set -a; . "$HOME/app.env"; set +a
export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1
# No MSBuild or compiler servers left running after the push: they would
# hold memory, and the deploy lock, until killed.
export DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDDISABLENODEREUSE=1 UseSharedCompilation=false
# The web project: PROJECT in ~/app.env, or the only one in the repository.
project=${PROJECT:-$(grep -rlE --include='*.csproj' 'Microsoft\.NET\.Sdk\.Web"' . || true)}
[ -n "$project" ] && [ "$(printf '%s\n' "$project" | wc -l)" = 1 ] ||
  fail "set PROJECT in ~/app.env to the web project's .csproj (found: ${project:-none})"
dotnet publish "$project" -c Release -o "$release" --disable-build-servers 9>&-
name=$(dotnet msbuild "$project" -getProperty:AssemblyName -p:Configuration=Release 9>&-)
mkdir -p "$release/bin" && ln -s "../$name" "$release/bin/app"
"$HOME/bin/app-backup" deploy >/dev/null  # the new version may migrate when it starts
if [ -n "${MIGRATE_COMMAND:-}" ]; then
  bash -c "$MIGRATE_COMMAND" 9>&-
fi

echo "==> Starting the new version"
ln -sfn "$release" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app"
sudo systemctl restart app
deadline=$((SECONDS + 60))  # wait up to a minute for an answer
while [ $SECONDS -lt $deadline ]; do
  code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://127.0.0.1:8000/ || true)
  case $code in 000|5??) sleep 1 ;; *) break ;; esac
done
case $code in
  000|5??) fail "the new version answers HTTP $code (journalctl -u app -n 50)" ;;
esac
trap - ERR
rm -rf "$src"
ls -1d "$HOME"/releases/*/ | head -n -3 | xargs -r rm -rf  # keep 3
echo "==> Deployed ${rev:0:7}: HTTP $code on port 8000"
EOF
chmod +x ~/app.git/hooks/pre-receive
```

The first build downloads NuGet packages into `~/.nuget/packages`, where
later builds find them. The hook counts any answer on port 8000 below
500 as up, so a home page that redirects to a login is fine.

### Start a new app

Skip to [Deploy and check](#deploy-and-check) if you brought a
repository. Otherwise, make a Razor Pages app from Microsoft's
`webapp` template, with EF Core for SQLite and the `dotnet-ef` tool in a
tool manifest. Floating `10.0.*` versions take each patch release on the
next build:

```bash
rm -rf /tmp/new-app && mkdir /tmp/new-app && cd /tmp/new-app
git init -q -b main
export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1
dotnet new webapp --name MyApp --output .
dotnet new gitignore
printf '\n# Local SQLite databases and Data Protection keys\n*.db\n*.db-*\nkeys/\n' >> .gitignore
dotnet new tool-manifest
dotnet tool install dotnet-ef --version '10.0.*'
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version '10.0.*'
dotnet add package Microsoft.EntityFrameworkCore.Design --version '10.0.*'
echo "ConnectionStrings__Default='Data Source=/home/exedev/data/app.db'" >> ~/app.env
```

The data model, in `Data/AppDb.cs`:

```bash
mkdir -p /tmp/new-app/Data
cat > /tmp/new-app/Data/AppDb.cs <<'EOF'
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

namespace MyApp.Data;

public class Message
{
    public int Id { get; set; }
    [MaxLength(320)] public required string Author { get; set; }
    [MaxLength(280)] public required string Body { get; set; }
    public DateTime Created { get; set; }
}

public class AppDb(DbContextOptions<AppDb> options) : DbContext(options)
{
    public DbSet<Message> Messages => Set<Message>();
}
EOF
```

The exe.dev sign-in, in `ExeDevAuthentication.cs`. It reads the headers
the proxy sets, gives emails in `AdminEmails` the `admin` role, and sends
signed-out visitors who need to sign in to exe.dev's login page:

```bash
cat > /tmp/new-app/ExeDevAuthentication.cs <<'EOF'
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;

namespace MyApp;

/// <summary>
/// Signs visitors in with their exe.dev account. exe.dev's HTTPS proxy adds
/// X-ExeDev-Email and X-ExeDev-UserID to requests from signed-in visitors
/// and removes any a visitor sends (https://exe.dev/docs/login-with-exe).
/// Safe only behind the proxy: Kestrel listens on 127.0.0.1, so nothing
/// but the proxy and programs on the VM can reach it to set the header.
/// </summary>
public class ExeDevAuthentication(
    IOptionsMonitor<AuthenticationSchemeOptions> options,
    ILoggerFactory logger,
    UrlEncoder encoder,
    IConfiguration config)
    : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
    public const string SchemeName = "ExeDev";

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        string email = Request.Headers["X-ExeDev-Email"].ToString().Trim().ToLowerInvariant();
        if (email == "")
            return Task.FromResult(AuthenticateResult.NoResult());

        var claims = new List<Claim>
        {
            new(ClaimTypes.Name, email),
            new(ClaimTypes.Email, email),
            new(ClaimTypes.NameIdentifier, Request.Headers["X-ExeDev-UserID"].ToString()),
        };
        // AdminEmails in ~/app.env: comma-separated exe.dev emails.
        string[] admins = (config["AdminEmails"] ?? "").Split(',',
            StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
        if (admins.Contains(email, StringComparer.OrdinalIgnoreCase))
            claims.Add(new(ClaimTypes.Role, "admin"));

        var user = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName));
        return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(user, SchemeName)));
    }

    // [Authorize] for a signed-out visitor: exe.dev's login, then back here.
    protected override Task HandleChallengeAsync(AuthenticationProperties properties)
    {
        string back = Request.PathBase + Request.Path + Request.QueryString;
        Response.Redirect("/__exe.dev/login?redirect=" + Uri.EscapeDataString(back));
        return Task.CompletedTask;
    }
}
EOF
```

`Program.cs`, replacing the template's. It trusts the proxy's forwarded
headers, keeps Data Protection keys in `~/data`, signs visitors in with
exe.dev, migrates the database on start, and adds a small JSON API next
to the pages:

```bash
cat > /tmp/new-app/Program.cs <<'EOF'
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using MyApp;
using MyApp.Data;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppDb>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("Default") ?? "Data Source=app.db"));

// exe.dev's HTTPS proxy ends TLS and connects from 127.0.0.1 with the
// visitor's scheme and address in X-Forwarded-Proto and X-Forwarded-For.
// Only loopback is trusted by default, which is where the proxy connects from.
builder.Services.Configure<ForwardedHeadersOptions>(options =>
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);

// Keys for cookies and antiforgery tokens: on the VM's disk, under a fixed
// name, so they survive deploys (each release is a new directory).
builder.Services.AddDataProtection()
    .SetApplicationName("MyApp")
    .PersistKeysToFileSystem(new DirectoryInfo(builder.Configuration["DataProtectionKeys"] ?? "keys"));

// Visitors are signed in with their exe.dev account (ExeDevAuthentication.cs).
builder.Services.AddAuthentication(ExeDevAuthentication.SchemeName)
    .AddScheme<AuthenticationSchemeOptions, ExeDevAuthentication>(ExeDevAuthentication.SchemeName, null);
builder.Services.AddAuthorization();

var app = builder.Build();

// Apply any migrations the database hasn't had yet.
using (var scope = app.Services.CreateScope())
{
    scope.ServiceProvider.GetRequiredService<AppDb>().Database.Migrate();
}

app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
// No UseHttpsRedirection or UseHsts: exe.dev's proxy does both.
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapStaticAssets();
app.MapRazorPages().WithStaticAssets();
app.MapGet("/api/messages", async (AppDb db) =>
    await db.Messages.OrderByDescending(m => m.Id).Take(100).ToListAsync());

app.Run();
EOF
```

The guestbook, replacing the template's home page:

```bash
cd /tmp/new-app
cat > Pages/Index.cshtml.cs <<'EOF'
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using MyApp.Data;

namespace MyApp.Pages;

public class IndexModel(AppDb db) : PageModel
{
    public List<Message> Messages { get; private set; } = [];

    [BindProperty, Required, StringLength(280)]
    public string Body { get; set; } = "";

    public async Task OnGetAsync() =>
        Messages = await db.Messages.OrderByDescending(m => m.Id).Take(100).ToListAsync();

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            await OnGetAsync();
            return Page();
        }
        db.Messages.Add(new Message
        {
            Author = User.Identity?.Name ?? "a visitor",
            Body = Body.Trim(),
            Created = DateTime.UtcNow,
        });
        await db.SaveChangesAsync();
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostDeleteAsync(int id)
    {
        if (!User.IsInRole("admin"))
            return Forbid();
        await db.Messages.Where(m => m.Id == id).ExecuteDeleteAsync();
        return RedirectToPage();
    }
}
EOF
cat > Pages/Index.cshtml <<'EOF'
@page
@model IndexModel
@{
    ViewData["Title"] = "Guestbook";
}

<h1>Guestbook</h1>
@if (User.Identity?.IsAuthenticated == true)
{
    <p>Signed in with exe.dev as <strong>@User.Identity.Name</strong>@(User.IsInRole("admin") ? " (admin)" : "").</p>
}
else
{
    <p>You're not signed in. <a href="/__exe.dev/login?redirect=/">Sign in with exe.dev</a></p>
}

<form method="post" class="d-flex gap-2 my-3">
    <input asp-for="Body" class="form-control" placeholder="Say hello" />
    <button class="btn btn-primary">Sign</button>
</form>
<span asp-validation-for="Body" class="text-danger"></span>

<ul class="list-unstyled">
    @foreach (var m in Model.Messages)
    {
        <li class="mb-2">
            <strong>@m.Author</strong>: @m.Body
            @if (User.IsInRole("admin"))
            {
                <form method="post" asp-page-handler="Delete" asp-route-id="@m.Id" class="d-inline">
                    <button class="btn btn-link btn-sm p-0 ms-2">delete</button>
                </form>
            }
        </li>
    }
    @if (Model.Messages.Count == 0)
    {
        <li>No messages yet. Be the first.</li>
    }
</ul>
EOF
```

Create the first migration, check the build, then commit and push to the
VM's repository. The push deploys:

```bash
cd /tmp/new-app
dotnet ef migrations add Initial
dotnet build -warnaserror --disable-build-servers
git add .
git -c user.name="$(hostname)" -c user.email="exedev@$(hostname).exe.xyz" commit -qm "A guestbook: Razor Pages, EF Core and SQLite"
git push ~/app.git HEAD:main
```

The output ends with `==> Deployed` and a commit. The code now lives in
`~/app.git` (the owner clones it from there), so remove the scratch copy
and stop the compiler servers the `dotnet ef` build left running:

```bash
cd ~ && rm -rf /tmp/new-app && dotnet build-server shutdown
```

### Deploy and check

If you brought a repository, set `PROJECT` in `~/app.env` if it has more
than one web project (`PROJECT=src/Web/Web.csproj`), and add the
settings it reads as `Section__Key` lines (see its README and
`appsettings.json`). Keep SQLite files in `~/data`. Then deploy its
default branch:

```bash
~/app.git/hooks/pre-receive HEAD
```

(A new app deployed when you pushed it.) Check, for either kind:

```bash
systemctl is-enabled app; systemctl is-active app
readlink ~/app
ss -ltn 'sport = :8000'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/
```

Expect `enabled`, `active`, the release directory, a listener on
`127.0.0.1:8000` only, and `200` (or your home page's usual status, such
as a `302` to a login page). For a new app, check the database, the
sign-in, and the forwarded headers:

```bash
curl -s http://127.0.0.1:8000/ | grep -o 'No messages yet'
curl -s -H "X-ExeDev-Email: $(grep -oP '^AdminEmails=\K[^,]*' ~/app.env)" http://127.0.0.1:8000/ | grep -o '(admin)'
curl -s http://127.0.0.1:8000/api/messages; echo
sqlite3 ~/data/app.db 'SELECT MigrationId FROM __EFMigrationsHistory' 'PRAGMA journal_mode'
ls ~/data/keys
```

Expect `No messages yet`, `(admin)`, `[]`, the `Initial` migration and
`wal`, and a `key-*.xml` file.

### Check the backup

Take the first backup by hand, then open it in a scratch directory, never
over `~/data`, to check that it holds what a restore needs:

```bash
latest=$(~/bin/app-backup manual)
rm -rf /tmp/restore-check && mkdir /tmp/restore-check
tar -xzf "$latest" -C /tmp/restore-check
ls -A /tmp/restore-check /tmp/restore-check/data
git -C ~/app.git bundle verify /tmp/restore-check/app.bundle
find /tmp/restore-check/data -type f \( -name '*.db' -o -name '*.sqlite' -o -name '*.sqlite3' \) |
  while read -r db; do echo "$db: $(sqlite3 "$db" 'PRAGMA integrity_check')"; done
rm -rf /tmp/restore-check
```

Expect `app.bundle`, `app.env`, and `data` (with `app.db` and `keys` for
a new app); `The bundle records a complete history`; and `ok` for each
database.

Setup is done. Continue with [Open your app](#open-your-app).

</details>

<details id="restore" class="dp-details">
<summary>Restore a backup</summary>

### On the same VM

On the VM, pick the archive (`ls -lt ~/backups`), unpack it, and swap
its `data` in while the app is stopped. The current data is kept aside:

```bash
backup=~/backups/app-nightly-20261116-030512.tar.gz   # the one you want
rm -rf /tmp/restore && mkdir /tmp/restore && tar -xzf "$backup" -C /tmp/restore
sudo systemctl stop app
mv ~/data ~/data.before-restore-$(date +%s)
cp -a /tmp/restore/data ~/data
sudo systemctl start app
```

Open the app and check your data. `~/app.env` is in `/tmp/restore` too, if
you need an old setting back. Delete `~/data.before-restore-*` when you're
sure. If the backup is older than the code's migrations, the app applies
the missing ones when it starts.

### On a new VM

Create the VM and follow [Set up by hand](#create-the-vm) up to, but not
including, "Get the code". Copy the archive over from your computer
(`scp app-nightly-20261116-030512.tar.gz my-aspnet.exe.xyz:`), then on the VM:

```bash
rm -rf /tmp/restore && mkdir /tmp/restore && tar -xzf ~/app-nightly-20261116-030512.tar.gz -C /tmp/restore
git clone --bare /tmp/restore/app.bundle ~/app.git && git -C ~/app.git remote remove origin
install -m 600 /tmp/restore/app.env ~/app.env
rm -rf ~/data && cp -a /tmp/restore/data ~/data
```

Then follow [Add the deploy hook](#add-the-deploy-hook) and deploy with
`~/app.git/hooks/pre-receive HEAD`. On your computer, point the `exe`
remote at the new VM: `git remote set-url exe <new-vm>.exe.xyz:app.git`.
The Data Protection keys came along in `data/keys`, so sign-ins and
forms carry on.

</details>

<details id="update" class="dp-details">
<summary>Update .NET and your packages</summary>

### Patches

Microsoft ships .NET patches on the second Tuesday of each month, and
Ubuntu publishes them through `apt`. On the VM:

```bash
sudo apt-get update && sudo apt-get install --only-upgrade -y dotnet-sdk-10.0
dotnet --list-runtimes
~/app.git/hooks/pre-receive HEAD
```

The last line republishes `main` against the new SDK and restarts the app
on the new runtime. A plain `sudo apt-get upgrade` does the same for the
rest of Ubuntu.

### Packages

NuGet packages are versioned in your `.csproj` and travel through git.
On your computer, `dotnet list package --outdated` shows what's newer;
change the versions (or `dotnet add package <name>` for the latest), test,
commit, and push. A new app's `10.0.*` versions pick up patch releases on
every build.

### Use .NET 11

.NET 11 is a standard-term release, supported until November 2028, the
same day as .NET 10. Ubuntu 24.04's feed doesn't carry it, so install it
with Microsoft's
[install script](https://learn.microsoft.com/dotnet/core/tools/dotnet-install-script)
into its own directory, next to the packaged .NET 10:

```bash
curl -fsSL https://dot.net/v1/dotnet-install.sh -o /tmp/dotnet-install.sh
sudo bash /tmp/dotnet-install.sh --channel 11.0 --install-dir /opt/dotnet11
/opt/dotnet11/dotnet --list-sdks
printf 'DOTNET_ROOT=/opt/dotnet11\nPATH=/opt/dotnet11:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n' >> ~/app.env
```

The last line points the hook's builds and the app at it. A `net10.0`
build won't start on it, so push the retargeted app right away: on your
computer, with .NET 11 installed there too, change `TargetFramework` to
`net11.0` and package versions to `11.0.*`, run
`dotnet tool update dotnet-ef --version '11.0.*'`, commit, and push. The
script doesn't update itself: rerun its second line for each monthly
patch, then redeploy.

</details>

<details id="sql-server" class="dp-details">
<summary>Use SQL Server</summary>

If your app is built for SQL Server, run it next to the app in Microsoft's
Linux container, `mcr.microsoft.com/mssql/server:2025-latest` (SQL Server
2025). It's x86-64 only and needs at least **2 GB of memory**; give it a
VM with 4 GB or more (`ssh exe.dev resize`, or `--memory=8GB` on a new VM).

Pick the edition with `MSSQL_PID`. The container is bring-your-own-license:

- `Express`: free, including in production. Each database is limited to
  50 GB, and the engine to 1,410 MB of buffer pool and 4 cores.
- `StandardDeveloper` or `EnterpriseDeveloper`: every feature of Standard
  or Enterprise, free, but only for development and testing, never
  production.
- `Standard` or `Enterprise`: only with a license you've bought.

**First, a disk it can use.** SQL Server only supports disks with
sectors of 4 KB or less, and an exe.dev VM's disk reports 16 KB: on it,
SQL Server crashes at startup (a "Stack Overflow" after "misaligned log
IOs" in its log). So give it a file system of its own, in a file on the
VM's disk, with 4 KB sectors. **On the VM** (make the file as large as
your databases will grow; it only takes the space it uses):

```bash
mkdir -p ~/mssql/data && cd ~/mssql
truncate -s 20G disk.img
dev=$(sudo losetup -b 4096 -f --show disk.img) && sudo mkfs.ext4 -q "$dev" && sudo losetup -d "$dev"
sudo tee /etc/systemd/system/mssql-disk.service >/dev/null <<'EOF'
[Unit]
Description=SQL Server's file system: ~/mssql/disk.img, 4 KB sectors, on ~/mssql/data
RequiresMountsFor=/home/exedev
Before=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/sh -c 'mount "$(losetup -b 4096 -f --show /home/exedev/mssql/disk.img)" /home/exedev/mssql/data'
ExecStop=/bin/sh -c 'umount /home/exedev/mssql/data; losetup -d "$(losetup -nO NAME -j /home/exedev/mssql/disk.img)"'

[Install]
WantedBy=docker.service multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now mssql-disk.service
sudo chown 10001:0 data
lsblk -o NAME,PHY-SEC,MOUNTPOINT "$(findmnt -no SOURCE data)"
```

Expect a loop device with `4096` mounted on `/home/exedev/mssql/data`.
Then make a password and start SQL Server with Docker Compose. It
listens on 127.0.0.1 only:

```bash
sudo systemctl enable --now docker.service
cd ~/mssql
[ -e .env ] || (umask 077; echo "MSSQL_SA_PASSWORD=A$(openssl rand -hex 16)" > .env)
cat > compose.yaml <<'EOF'
services:
  mssql:
    image: mcr.microsoft.com/mssql/server:2025-latest
    restart: unless-stopped
    environment:
      ACCEPT_EULA: "Y"
      MSSQL_PID: Express
      MSSQL_SA_PASSWORD: ${MSSQL_SA_PASSWORD}
      MSSQL_MEMORY_LIMIT_MB: "2048"
    ports:
      - 127.0.0.1:1433:1433
    volumes:
      - ./data:/var/opt/mssql
EOF
docker compose up -d
```

`ACCEPT_EULA=Y` accepts
[Microsoft's license terms](https://go.microsoft.com/fwlink/?linkid=857698).
Wait half a minute for the first start, then check:

```bash
set -a; . ~/mssql/.env; set +a
docker compose -f ~/mssql/compose.yaml exec mssql /opt/mssql-tools18/bin/sqlcmd \
  -S localhost -U sa -P "$MSSQL_SA_PASSWORD" -C -h -1 \
  -Q "SET NOCOUNT ON; SELECT CAST(SERVERPROPERTY('Edition') AS varchar(40)); CREATE DATABASE app;"
```

Expect `Express Edition (64-bit)`. Then add
`Microsoft.EntityFrameworkCore.SqlServer`, call `UseSqlServer`, and put
the connection string in `~/app.env`, using the password from
`~/mssql/.env`:

```bash
set -a; . ~/mssql/.env; set +a
echo "ConnectionStrings__Default='Server=127.0.0.1,1433;Database=app;User Id=sa;Password=$MSSQL_SA_PASSWORD;TrustServerCertificate=True'" >> ~/app.env
```

`TrustServerCertificate=True` accepts the container's self-signed
certificate; the connection never leaves the VM. For a real deployment,
create a login for the app instead of using `sa`. The nightly
`app-backup` doesn't cover SQL Server: schedule `BACKUP DATABASE app TO
DISK = '/var/opt/mssql/backup/app.bak'` with `sqlcmd` in a timer, and copy
the `.bak` files (`sudo ls ~/mssql/data/backup`) off the VM.

</details>

<details id="troubleshooting" class="dp-details">
<summary>Something not working?</summary>

On the VM, the app's logs:

```bash
journalctl -u app -n 100 --no-pager
```

- **`git push` says `Deploy FAILED` and `pre-receive hook declined`.**
  The lines above it are the error, usually the same one `dotnet publish`
  gives on your computer. The running version didn't change; fix it and
  push again.
- **`set PROJECT in ~/app.env`.** The repository has no web project, or
  more than one; set `PROJECT` to the path of the one to deploy.
- **`NETSDK1045: The current .NET SDK does not support targeting .NET
  11.0`.** See [Use .NET 11](#update), or target `net10.0`.
- **`You must install or update .NET to run this application`** in the
  log: the app targets `net8.0` or `net9.0`, whose runtimes aren't
  installed (and are out of support). Retarget to `net10.0`.
- **`HTTP 000` in the failed deploy.** The new version exited or didn't
  listen on 127.0.0.1:8000 within a minute; `journalctl -u app -n 50` says why, often a
  missing connection string, or `Kestrel:Endpoints` in `appsettings.json`
  overriding `ASPNETCORE_URLS`.
- **`PendingModelChangesWarning`** at startup: the model changed without
  a migration. Run `dotnet ef migrations add <Name>` and push it.
- **Links or redirects use `http://`, or every visitor has IP
  127.0.0.1.** `app.UseForwardedHeaders()` is missing, or comes after
  the middleware that reads the scheme; see [Behind the proxy](#behind-the-proxy).
- **Everyone is signed out, or forms fail with "The antiforgery token
  could not be decrypted", after each deploy.** Data Protection keys
  aren't persisted under a fixed application name; see
  [Behind the proxy](#behind-the-proxy).
- **Disk filling up.** `du -sh ~/releases/* ~/backups ~/.nuget/packages`;
  the hook keeps three releases, and `dotnet nuget locals all --clear`
  empties NuGet's caches.

</details>

## Frequently asked questions

### Which .NET version does this use?

.NET 10, the long-term support release, from Ubuntu's own package feed, so `apt upgrade` brings its monthly security patches. .NET 11 (November 2026) is a standard-term release supported until the same date, November 2028; to use it, see [Use .NET 11](#update). .NET 8 and 9 reached end of support on November 10, 2026: retarget to `net10.0`.

### Do I need nginx in front of Kestrel?

No. exe.dev's proxy already ends TLS, redirects to HTTPS, sends HSTS, and limits who gets in, so Kestrel listens on 127.0.0.1:8000 and the proxy talks to it directly. Add nginx only if you want it for something specific, such as serving a large directory of files.

### Can I use SQL Server?

Yes, in a container on the same VM, for development or for production with the free Express edition (50 GB per database, about 1.4 GB of buffer pool). It needs 2 GB of memory to itself, and a small loop-device file system, since it can't use the VM's 16 KB-sector disk directly. See [SQL Server](#sql-server). For most new apps, SQLite or [PostgreSQL](/deploy/postgres) is lighter.

### Does Blazor Server work?

Yes. Its SignalR connection uses WebSockets, which exe.dev's proxy passes through, private or public. A deploy restarts the app, so open circuits reconnect and lose in-memory state; see [Blazor and SignalR](#blazor-and-signalr).

### Are deploys zero-downtime?

No. A deploy restarts one Kestrel process: requests in flight finish, and new ones fail for the second or two the new version takes to start. The old version stays up while the new one builds, and a failed deploy puts it back. For true zero-downtime you'd run two copies behind a load balancer, which this recipe doesn't.

### Does it sleep, or have cold starts?

No. The VM is always on, so `BackgroundService`s, timers, and SignalR connections keep running. You pay for the VM, not per request; see [exe.dev plans](https://exe.dev/pricing).


## Related

- [Deploy a Go web app](https://exe-staging.dev/deploy/go.md): One Go binary on a VM of its own. git push to deploy.
- [Deploy a Node.js app](https://exe-staging.dev/deploy/nodejs.md): Your Express app on a server of its own. git push to deploy.
- [Deploy a Spring Boot app](https://exe-staging.dev/deploy/spring-boot.md): Your Spring Boot jar on a server of its own. git push to deploy.
- [Deploy a Django app](https://exe-staging.dev/deploy/django.md): Your Django app on a computer of its own. git push to deploy.
- [SQLite in production](https://exe-staging.dev/deploy/sqlite.md): One file on a real disk, streamed to your own bucket every second.
- [Self-host PostgreSQL](https://exe-staging.dev/deploy/postgres.md): Your own Postgres on a real disk, with backups you've actually restored.
