Skip to content

Deployment ​

Introduction ​

When you are ready to deploy your DotBlaze application to production, there are a few important things you can do to make sure it runs reliably. This page covers a plain Linux server with systemd; the same steps apply to containers, with the container runtime as the process supervisor.

Server Requirements ​

  • The ASP.NET Core 10 runtime (or the .NET 10 SDK if you build on the server).
  • The database server you configured (nothing extra for SQLite).
  • Node.js only on the machine that builds the frontend assets, not on the web server.

Building for Production ​

Building Frontend Assets ​

The compiled CSS and JavaScript in wwwroot/build are not committed, so build them before publishing. Use npm ci for a clean install from package-lock.json:

The template does not ship a lockfile. Run npm install once in development and commit the generated package-lock.json before using npm ci in deployment.

shell
npm ci
npm run build

Publishing the Application ​

Then publish the application. Build the assets first, so dotnet publish copies wwwroot/build into the output:

shell
dotnet publish -c Release -o ./publish

The output contains the compiled application (Razor views are compiled into it), and wwwroot. Copy the publish folder to the server, for example to /var/www/blog.

Configuration and Environment ​

Configuration classes are compiled into the application; published apps do not load config/*.cs as source files. DotBlaze reads .env and resolves relative storage/database paths against the content root, normally the published process's working directory. Start the app from its own folder (systemd's WorkingDirectory, a container's WORKDIR).

The .env file is not part of the publish output. In production, either create a .env file in the application folder on the server, or (preferably) provide the values as real environment variables, which always take precedence over .env. Any config key can also be overridden directly, for example database__connections__pgsql__host=db.internal. See Configuration.

Set APP_ENV=production on production servers (in .env or, preferably, the process environment). The template's .env.example uses APP_ENV=local, which enables Development; do not deploy that value. APP_ENV takes precedence over the .NET environment variables. Without it, existing ASP.NET Core environment selection still applies and defaults to Production. See environment configuration.

Put the application into maintenance mode while you deploy, if a migration or a restart would disturb visitors: dotblaze down --retry=60 before, dotblaze up after.

Running Migrations ​

Console commands run through the application itself. From a source checkout, run:

shell
dotblaze migrate

From a published application, pass the command to the compiled DLL instead:

shell
cd /var/www/blog
dotnet Blog.dll migrate

Unlike Laravel, migrate does not ask for confirmation in production; it simply runs the pending migrations. Run it as part of each deployment, before restarting the web server and the workers. dotnet Blog.dll db:check compares your models with the database schema and exits with code 1 if they differ, which makes it a useful deployment check. See Migrations and Console Commands.

Running the Web Server ​

A DotBlaze application is a normal ASP.NET Core application running on Kestrel. A systemd unit keeps it running and restarts it after a crash or reboot:

ini
# /etc/systemd/system/blog-web.service
[Unit]
Description=Blog web server
After=network.target

[Service]
WorkingDirectory=/var/www/blog
ExecStart=/usr/bin/dotnet /var/www/blog/Blog.dll
Restart=always
RestartSec=5
User=www-data
Environment=ASPNETCORE_URLS=http://127.0.0.1:5000
Environment=APP_ENV=production
Environment=app__debug=false

[Install]
WantedBy=multi-user.target
shell
sudo systemctl enable --now blog-web

Reverse Proxy ​

Put a reverse proxy such as Nginx in front of Kestrel to terminate TLS:

nginx
server {
    listen 443 ssl;
    server_name blog.example.com;
    # ssl_certificate ...

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

The template and sample install global TrustProxies and TrustHosts middleware from AppServiceProvider.Register, before routing and authentication. Configure the actual proxy IPs or CIDRs; an empty list trusts no proxy:

csharp
services.AddTrustProxies(options =>
{
    options.KnownProxies.Add(System.Net.IPAddress.Parse("127.0.0.1"));
    // Or: options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("10.0.0.0/24"));
    options.ForwardLimit = 1;
});
services.AddTrustHosts(options => options.Subdomains = false);

Keep this order: proxy headers are applied first, then the resulting host is validated. TrustProxies uses ASP.NET Core's forwarded-header processing for X-Forwarded-For, -Proto, -Host, and -Prefix. Do not also enable ASPNETCORE_FORWARDEDHEADERS_ENABLED or install a second forwarded-header middleware: that can process headers before these trust rules.

TrustHosts defaults to the host in APP_URL and its subdomains, like Laravel. Set Subdomains = false when only the exact host is trusted; this is recommended if subdomains are user-controlled. Other hosts receive 400 before application code runs. Set APP_URL to the public HTTPS origin in production; missing or invalid configuration stops startup. For multiple trusted domains, set options.Hosts = ["blog.example.com", "other.example.com"] explicitly (host names only, no schemes or ports). The default host check is skipped in Development and Testing, like Laravel; explicit Hosts are checked in every environment.

Only trust proxy addresses you control, keep Kestrel inaccessible to the public, and ensure proxies replace forwarded headers rather than passing client-supplied values through.

Error Page ​

With debugging disabled, an unhandled exception returns a 500 | Server Error page (or { "message": "Server Error" } for JSON requests) without details. Set app__debug=false in production: an explicit app.debug=true overrides the environment default. The exception is logged either way. Customize pages in resources/views/errors (for example 404.blade.html or 500.blade.html), and report exceptions with Exceptions.Report. See Error Handling.

Data Protection Keys ​

Several DotBlaze features rely on ASP.NET Core Data Protection, keyed by the application key (APP_KEY), like in Laravel:

  • Crypt.Encrypt / Crypt.Decrypt (see Encryption),
  • the authentication cookie (see Authentication),
  • CSRF tokens and TempData, which carries flash messages, validation errors, and old input across redirects,
  • signed URLs (see URL generation) and the "remember me" cookie,
  • the signed snapshots of live components and their temporary upload references.

Set the same APP_KEY on every server and queue worker, for example as an environment variable. Generate one with dotblaze key:generate --show. With an APP_KEY, nothing is written to disk, and servers can be replaced freely.

WARNING

Never change APP_KEY on a running application: every user is logged out, and data encrypted with Crypt can no longer be read.

Without an APP_KEY, Data Protection generates its own keys and stores them in storage/framework/keys under the content root (override the folder with app.keys_path in config/App.cs, or app__keys_path in the environment). The folder must then survive deploys, and with several servers every instance must share it, or use another key store, such as Redis (keys_driver = "redis" in config/App.cs, see Redis).

To use another key store for those generated keys, extend DotBlaze's registration in a service provider. Calling AddDataProtection() again returns the builder for the same services, and the last key store registered wins. The example below stores keys in a database with the Microsoft.AspNetCore.DataProtection.EntityFrameworkCore package; KeysDbContext is your own EF Core context that implements IDataProtectionKeyContext:

csharp
using Microsoft.AspNetCore.DataProtection;

namespace Blog.Providers;

public class AppServiceProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config)
    {
        services.AddDataProtection()
            .PersistKeysToDbContext<KeysDbContext>();
    }
}

ASP.NET Core offers other key stores too, such as Azure Blob Storage or Redis. Consider protecting keys at rest as well (for example ProtectKeysWithCertificate).

Running Queue Workers ​

If you use the database queue driver, jobs are processed by a separate worker process:

shell
dotnet Blog.dll queue:work --queue=default

Supervising the Worker ​

Run workers under a process supervisor, as in Laravel. This is not optional: .NET cannot forcibly stop running code, so when a job ignores its timeout, queue:work marks the job as failed and exits with code 1. The supervisor must then start a fresh worker. A systemd unit:

ini
# /etc/systemd/system/blog-worker@.service
[Unit]
Description=Blog queue worker %i
After=network.target

[Service]
WorkingDirectory=/var/www/blog
ExecStart=/usr/bin/dotnet /var/www/blog/Blog.dll queue:work --queue=default
Restart=always
RestartSec=3
User=www-data
# queue:work finishes the current job on SIGTERM (systemd's default) and Ctrl+C; give the longest job time to complete.
TimeoutStopSec=120

[Install]
WantedBy=multi-user.target
shell
# Two workers
sudo systemctl enable --now blog-worker@1 blog-worker@2

Running several workers is safe: jobs are claimed with a conditional UPDATE, so a job never runs on two workers at once, on every supported database.

NOTE

queue:work finishes the current job on both SIGTERM (the default stop signal of systemd and Docker) and SIGINT. Give the unit enough TimeoutStopSec for your longest job. A job interrupted by a hard kill is picked up again after retry_after.

Workers load your application code once at startup. After each deployment, restart them so they run the new code:

shell
sudo systemctl restart 'blog-worker@*'

TIP

Instead of one unit per worker, run a single queue:manager unit: it starts the workers configured in config/Queue.cs, balances them between queues, and restarts them by itself. After a deploy, dotnet Blog.dll queue:manager:terminate makes it stop gracefully so systemd starts it with the new code. See The Queue Manager.

Job Timeouts and retry_after ​

Two settings work together, as in Laravel:

  • retry_after on the queue connection (config/Queue.cs, default 90 seconds): a job reserved longer than this is considered lost and is handed to another worker.
  • Timeout on a job class: the maximum run time per attempt. When it passes, the job's Cancellation token is cancelled and the attempt counts as failed. If the job is still running 10 seconds later (it ignored the token), the worker exits with code 1 as described above.
csharp
public class GenerateReport : Job, IShouldQueue
{
    public override TimeSpan? Timeout => TimeSpan.FromSeconds(60);

    public override async Task Handle()
    {
        await Task.Delay(1000, Cancellation);   // pass the token to async calls
    }
}

A job's Timeout plus the 10-second grace period must be shorter than retry_after; otherwise a job that is still running would be picked up a second time. queue:work checks every job class at startup and refuses to start, with an error naming the offending jobs, if any timeout is too long. Raise retry_after or lower the timeout.

Running the Worker Inside the Web Application ​

For small applications you may run a worker inside the web process instead of a separate service, in config/Queue.cs:

csharp
public class QueueConfig : ConfigFile
{
    public override object Values() => new
    {
        @default = "database",
        worker = true,
        worker_queues = "default,emails",
        connections = new
        {
            database = new { driver = "database", queue = "default", retry_after = 90 },
        },
    };
}

The in-app worker cannot exit when a job ignores its timeout. Instead, that job goes straight to failed_jobs without a retry (so it never runs twice at once) and keeps running in the background. For workloads with long or unreliable jobs, prefer a supervised queue:work process.

Running the Scheduler ​

Scheduled tasks need schedule:run every minute. With cron:

shell
# crontab -u www-data -e
* * * * * cd /var/www/blog && /usr/bin/dotnet Blog.dll schedule:run >> /dev/null 2>&1

Or run schedule:work as a service, next to the queue workers:

ini
# /etc/systemd/system/blog-scheduler.service
[Unit]
Description=Blog scheduler
After=network.target

[Service]
WorkingDirectory=/var/www/blog
ExecStart=/usr/bin/dotnet /var/www/blog/Blog.dll schedule:work
Restart=always
User=www-data

[Install]
WantedBy=multi-user.target

Restart it after each deployment, like the workers. On several servers, either run the scheduler on one of them, or use OnOneServer() on the tasks with a shared redis cache.

Running on Multiple Servers ​

When the application runs on more than one server:

  • Set the same APP_KEY on all servers and workers.

  • Use a database server rather than SQLite.

  • Use the s3 disk (or another shared disk) instead of local/public for uploaded files. See File Storage.

  • Run migrations once per deployment, from one machine.

  • Use a shared session/cache store for authentication state and scheduler locks, and a broadcasting backplane when events originate outside the connected web process.

Complete Example: Publish and Smoke-Test ​

Starting from the working Blog application, build on a machine with the .NET SDK and Node.js. Commit the lockfile created by the first development npm install, then run:

shell
npm ci
npm run build
dotnet publish Blog.csproj -c Release -o publish

Deploy publish to the working directory used by the service units above. Provision APP_KEY, database credentials, APP_URL, ASPNETCORE_ENVIRONMENT=Production, and app__debug=false through the server's environment. Keep writable database/uploads/key storage outside disposable release directories or mount persistent volumes.

From that published directory, with the same environment as the services:

shell
dotnet Blog.dll migrate
dotnet Blog.dll db:check
dotnet Blog.dll route:list

Expected: pending migrations apply, model columns match, and the posts routes exist. Restart the web service, workers, and scheduler after deployment. Check /, /login, one authenticated read, and a form write; static CSS/JS should return 200 and a guest's protected page should redirect to login.

For Nginx/SignalR, retain WebSocket upgrade headers. Accept forwarded headers only from your trusted reverse proxy and keep the Kestrel port private; inspect the effective ASP.NET Core proxy configuration rather than trusting arbitrary client X-Forwarded-* values. A local build/test cannot verify the target server's TLS, proxy trust, storage permissions, or external service credentials.