Aspire database patterns
Most Aspire solutions include at least one database. During development you create that database, fill it with sample data, change its schema as your app evolves, and decide whether its data should survive a restart. When you deploy, you decide where the database runs and how schema changes reach it. This article describes the options Aspire gives you for each of these tasks, with examples you can adapt for your own solution.
The examples on this page use PostgreSQL but the same patterns apply to other database integrations such as SQL Server, MySQL, and MongoDB. Where an example needs an Object-Relational Mapper (ORM), it uses Entity Framework Core (EF Core) for .NET apps or Drizzle for JavaScript and TypeScript apps. Select your ORM to see only the examples that use it:
Use this table to find the right approach for your requirements:
| What do you want to do? | Where do you want to do it? | Options |
|---|---|---|
| Create a database | In the AppHost | Add a database resource |
| In an orchestrated app | On startup or with a custom command | |
| In a dashboard REPL terminal | Run commands or a script | |
| Seed a database | In an orchestrated app | On startup or with a custom command |
| Use EF Core or Drizzle migrations | ||
| In a dashboard REPL terminal | Run a script | |
| Modify a database schema | In an orchestrated app | Apply migrations on startup |
| Apply migrations with a custom command | ||
| In a dashboard REPL terminal | Run a script | |
| Persist a database across restarts | In the AppHost | Data volumes, bind mounts, and persistent lifetimes |
| Deploy a database | In the AppHost | A container database or a managed database service |
In this article, a script is any program that works with the database. It can be a SQL file, a shell script, or a program written in a language such as JavaScript or Python.
Create a database
Section titled “Create a database”A database server, such as a PostgreSQL container, can host many databases. Your app needs a specific database on that server before it can create tables or store data. You can create that database from the AppHost, from your app’s code, or by hand in the dashboard.
Create a database in the AppHost
Section titled “Create a database in the AppHost”The simplest way to create a database is to add a database resource to the server resource in your AppHost. The PostgreSQL resources in the examples on this page come from the 📦 Aspire.Hosting.PostgreSQL package. Call AddDatabaseaddDatabaseAddDatabase on the server resource, then reference the database from the app that uses it:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts') .withReference(catalogdb) .waitFor(catalogdb);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb) .WaitFor(catalogdb);
builder.Build().Run();When the server resource is ready, Aspire creates the database if it doesn’t already exist. WithReferencewithReferenceWithReference passes the database’s connection information to the app, and WaitForwaitForWaitFor makes sure the app doesn’t start until the database is available.
To control how the database is created, for example to set a collation or an owner, replace the default creation script by using WithCreationScriptwithCreationScriptWithCreationScript. SQL Server and MySQL support the same method.
For more information, see Add PostgreSQL resource with database scripts. For details on how Aspire waits for the server to be ready, see AppHost eventing APIs.
Create a database in an orchestrated app
Section titled “Create a database in an orchestrated app”Sometimes the app needs to create its own database. For example, the app might connect to an existing server that isn’t modeled in your AppHost, or it might create one database for each tenant. In this case, reference the server resource instead of a database resource, so the app receives a connection to the server.
EF Core can create the database for you. When an app applies migrations, EF Core creates the database first if it doesn’t exist. EnsureCreatedAsync also creates the database, but it bypasses migrations, so use it only for prototypes and tests.
When a .NET app references a PostgreSQL server resource named postgres, Aspire passes a connection string to the server, without a database name. Add the database name to the connection string when you register the DbContext, then apply migrations when the app starts. This example assumes a DbContext named CatalogContext:
using Microsoft.EntityFrameworkCore;using Npgsql;
var builder = WebApplication.CreateBuilder(args);
builder.AddNpgsqlDbContext<CatalogContext>("postgres", configureSettings: settings =>{ settings.ConnectionString = new NpgsqlConnectionStringBuilder(settings.ConnectionString) { Database = "catalogdb" }.ConnectionString;});
var app = builder.Build();
if (app.Environment.IsDevelopment()){ using var scope = app.Services.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
// Creates catalogdb if it doesn't exist, then applies pending migrations. await context.Database.MigrateAsync();}
app.Run();Drizzle doesn’t create databases. Instead, connect to the server and run a CREATE DATABASE statement before you run migrations. When a JavaScript app references a PostgreSQL server resource named postgres, Aspire passes the server’s connection URI in the POSTGRES_URI environment variable:
import pg from 'pg';
const client = new pg.Client({ connectionString: process.env.POSTGRES_URI });await client.connect();
const { rowCount } = await client.query( 'SELECT 1 FROM pg_database WHERE datname = $1', ['catalogdb']);
if (rowCount === 0) { await client.query('CREATE DATABASE catalogdb');}
await client.end();You can run this code when the app starts, or from a custom command that you trigger from the dashboard. The Seed a database on startup or using a custom command section shows both approaches.
For the environment variables that Aspire passes to apps for each resource, see Connect to PostgreSQL.
Create a database in a dashboard REPL terminal
Section titled “Create a database in a dashboard REPL terminal”To create a database by hand, open the database’s own command-line client in the dashboard. Call WithReplwithReplWithRepl on the server resource to add a REPL command. The command opens psql in the dashboard’s terminal dock, already signed in with the resource’s credentials:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addPostgres('postgres').withRepl();
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
builder.AddPostgres("postgres").WithRepl();
builder.Build().Run();Run the app, then in the Aspire dashboard, select the REPL command on the postgres resource, and enter the statement:
CREATE DATABASE catalogdb;The SQL Server, MySQL, MongoDB, and Redis integrations also provide REPL commands. A database that you create by hand is lost when its container is removed, unless you persist the database.
For more information, see Open a database or cache REPL. For an overview of all terminal types, see Use interactive terminals in the dashboard.
Seed a database with sample data
Section titled “Seed a database with sample data”Seeding fills a database with data before you use it, such as a product catalog or a set of test customers. Seed data lets you develop and test features against realistic content. Because database containers start empty by default, automate seeding so that every run starts from a known state.
Seed a database in an orchestrated app
Section titled “Seed a database in an orchestrated app”When your app seeds the database, the seed logic lives in source control next to the model it depends on. You can run it every time the app starts, run it on demand, or include it in your migrations.
Seed a database on startup or using a custom command
Section titled “Seed a database on startup or using a custom command”To seed on startup, run the seed code after the app connects to the database and before it handles requests. Make the code idempotent: check whether the data already exists before you insert it, so a restart doesn’t add duplicate rows.
Configure seeding with the UseSeeding and UseAsyncSeeding options when you register the DbContext. EF Core runs this code when the database is created or migrated. Implement both options with the same logic, because the EF Core tools call the synchronous UseSeeding option. The following example seeds a product only when it doesn’t exist, and registers the seed code only in development:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.AddNpgsqlDbContext<CatalogContext>("catalogdb", configureDbContextOptions: options =>{ if (!builder.Environment.IsDevelopment()) { return; }
options.UseSeeding((context, _) => { var products = context.Set<Product>(); if (!products.Any(p => p.Name == "Sample product")) { products.Add(new Product { Name = "Sample product", Price = 9.99m }); context.SaveChanges(); } });
options.UseAsyncSeeding(async (context, _, cancellationToken) => { var products = context.Set<Product>(); if (!await products.AnyAsync(p => p.Name == "Sample product", cancellationToken)) { products.Add(new Product { Name = "Sample product", Price = 9.99m }); await context.SaveChangesAsync(cancellationToken); } });});
var app = builder.Build();
if (app.Environment.IsDevelopment()){ using var scope = app.Services.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
// Applies pending migrations, then runs the UseAsyncSeeding code. await context.Database.MigrateAsync();}
app.Run();To register the DbContext for SQL Server or MySQL instead, see Seed data using EF Core.
The drizzle-seed package generates realistic random data from your schema. The following example seeds the products table only when it’s empty:
import { drizzle } from 'drizzle-orm/node-postgres';import { seed } from 'drizzle-seed';import { products } from './schema.ts';
export async function seedDatabase() { const db = drizzle(process.env.CATALOGDB_URI!);
const existing = await db.select().from(products).limit(1); if (existing.length === 0) { await seed(db, { products }, { count: 50 }); }}Call seedDatabase() when the app starts. Aspire passes the CATALOGDB_URI environment variable because the app references a database resource named catalogdb.
To seed only when you choose, expose the seed code as an endpoint in your app, then add a custom HTTP command to the app resource. The command appears in the dashboard, and selecting it sends a request to the endpoint.
The endpoint adds the rows through the database context. It checks for existing rows first, so you can run the command more than once:
using Microsoft.EntityFrameworkCore;
// After you build the app...
if (app.Environment.IsDevelopment()){ app.MapPost("/admin/seed", async (CatalogContext context) => { if (!await context.Products.AnyAsync()) { context.Products.Add(new Product { Name = "Sample product", Price = 9.99m }); await context.SaveChangesAsync(); }
return Results.Ok(new { status = "Database seeded" }); });}Add the command to the app resource with WithHttpCommandwithHttpCommandWithHttpCommand:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api', '../Api/Api.csproj') .withReference(catalogdb) .waitFor(catalogdb) .withHttpCommand('/admin/seed', 'Seed database', { methodName: 'POST', description: 'Adds sample data to the catalog database.', confirmationMessage: 'Add sample data to the catalog database?', });
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb) .WaitFor(catalogdb) .WithHttpCommand( path: "/admin/seed", displayName: "Seed database", commandOptions: new HttpCommandOptions { Method = HttpMethod.Post, Description = "Adds sample data to the catalog database.", ConfirmationMessage = "Add sample data to the catalog database?" });
builder.Build().Run();The endpoint calls the seedDatabase function from the previous example:
import express from 'express';import { seedDatabase } from './seed.ts';
const app = express();
if (process.env.NODE_ENV === 'development') { app.post('/admin/seed', async (req, res) => { await seedDatabase(); res.json({ status: 'Database seeded' }); });}
// Add your other routes...
app.listen(process.env.PORT);Add the command to the app resource with WithHttpCommandwithHttpCommandWithHttpCommand:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts') .withHttpEndpoint({ env: 'PORT' }) .withReference(catalogdb) .waitFor(catalogdb) .withHttpCommand('/admin/seed', 'Seed database', { methodName: 'POST', description: 'Adds sample data to the catalog database.', confirmationMessage: 'Add sample data to the catalog database?', });
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddNodeApp("api", "../api", "src/index.ts") .WithHttpEndpoint(env: "PORT") .WithReference(catalogdb) .WaitFor(catalogdb) .WithHttpCommand( path: "/admin/seed", displayName: "Seed database", commandOptions: new HttpCommandOptions { Method = HttpMethod.Post, Description = "Adds sample data to the catalog database.", ConfirmationMessage = "Add sample data to the catalog database?" });
builder.Build().Run();The HTTP endpoint passes its port to the app in the PORT environment variable. The app must listen on process.env.PORT, otherwise the command can’t reach it.
Protect seed endpoints so that only the AppHost can call them, and don’t expose them in production. The examples in Modify a schema with a custom command show how to send a shared secret with each request.
For more information, see Custom HTTP commands. To run logic in the AppHost itself instead of calling an endpoint, see Custom resource commands.
Seed a database using ORM migrations
Section titled “Seed a database using ORM migrations”You can also include seed data in your migrations. The data is then applied in order with your schema changes, and it reaches every environment that runs the migrations. Use this approach for reference data that your app needs, such as a list of countries or order statuses, rather than for large sets of test data.
Call HasData in OnModelCreating to define seed rows as part of your model. Each row needs a primary key value:
protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity<OrderStatus>().HasData( new OrderStatus { Id = 1, Name = "Pending" }, new OrderStatus { Id = 2, Name = "Shipped" }, new OrderStatus { Id = 3, Name = "Delivered" });}Then add a migration:
dotnet ef migrations add SeedOrderStatusesEF Core generates the insert, update, and delete statements needed to keep the rows in sync with the model. For more information, see Model managed data in the EF Core documentation.
Generate an empty custom migration:
npx drizzle-kit generate --custom --name=seed-order-statusesDrizzle Kit creates a SQL file in your migrations folder. Add your INSERT statements to that file:
INSERT INTO order_statuses (id, name) VALUES (1, 'Pending'), (2, 'Shipped'), (3, 'Delivered');Drizzle applies the file in order with your other migrations. Drizzle Kit sets the number prefix in the file name. For more information, see Custom migrations in the Drizzle documentation.
To learn how to apply migrations when your app runs, see Modify a database schema.
Seed a database in a dashboard REPL terminal
Section titled “Seed a database in a dashboard REPL terminal”To add data by hand, open the database’s REPL from the dashboard as described in Create a database in a dashboard REPL terminal, then paste your INSERT statements. Use the REPL to try out data or to fix a single row. For seed data that you need every time, save it as a script so you can repeat the process.
To run a SQL script automatically when the database container initializes, mount a folder of scripts into the container with WithInitFileswithInitFilesWithInitFiles:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');await postgres.withInitFiles('./postgres-init');
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
builder.AddPostgres("postgres") .WithInitFiles("./postgres-init");
builder.Build().Run();PostgreSQL runs the .sql and .sh files in the folder in alphabetical order, against the default postgres database. The scripts run before Aspire creates the databases in your AppHost, so a script that seeds catalogdb creates that database and connects to it first:
CREATE DATABASE catalogdb;\c catalogdb
CREATE TABLE IF NOT EXISTS products( id SERIAL PRIMARY KEY, name TEXT UNIQUE NOT NULL, price NUMERIC(10, 2) NOT NULL);
INSERT INTO products (name, price)VALUES ('Hiking boots', 89.99), ('Water bottle', 12.50), ('Trail map', 4.99)ON CONFLICT DO NOTHING;If your AppHost also adds catalogdb as a database resource, Aspire finds the existing database when it creates its databases and leaves it in place. An initialization script that creates tables can conflict with ORM migrations that create the same tables. Use initialization scripts for databases that your app doesn’t manage with migrations.
PostgreSQL runs these scripts only when it initializes an empty data directory. If you persist the database with a data volume, the scripts don’t run again until you remove the volume.
To run a separate seed program, add it to the AppHost as a resource that you start from the dashboard. Call WithExplicitStartwithExplicitStartWithExplicitStart so that the resource doesn’t run with the rest of the app. The resource receives the database’s connection information from its database reference, in the same way as the app.
This example adds a .NET console project that seeds the database. The project registers the DbContext in the same way as the app:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api-seed', '../SeedData/SeedData.csproj') .withReference(catalogdb) .waitFor(catalogdb) .withExplicitStart();
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddDotnetProject("api-seed", "../SeedData/SeedData.csproj") .WithReference(catalogdb) .WaitFor(catalogdb) .WithExplicitStart();
builder.Build().Run();This example runs a db:seed script from the app’s package.json file:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addJavaScriptApp('api-seed', './api', { runScriptName: 'db:seed' }) .withReference(catalogdb) .waitFor(catalogdb) .withExplicitStart();
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddJavaScriptApp("api-seed", "../api", "db:seed") .WithReference(catalogdb) .WaitFor(catalogdb) .WithExplicitStart();
builder.Build().Run();To seed, select Start on the api-seed resource in the dashboard. The resource’s console logs show the script’s output. To run a tool that isn’t part of your app, such as a CLI installed on your machine, use a process-backed resource command instead. For more information, see Process-backed resource commands.
For initialization script examples for SQL Server and MySQL, see Seed data using SQL scripts.
Modify a database schema
Section titled “Modify a database schema”As your app evolves, its tables and columns change. Most teams manage these changes with migrations: versioned files, kept in source control, that each describe one change to the schema. An ORM tracks which migrations a database has already applied, so it applies only the new ones. Your ORM generates migrations from changes to your model.
Run dotnet ef migrations add <name> to generate a C# migration from changes to your DbContext model. For more information, see Create migrations.
Run npx drizzle-kit generate to generate a SQL migration from changes to your schema file. For more information, see Migrations with Drizzle in the Drizzle documentation.
Apply schema migrations on startup
Section titled “Apply schema migrations on startup”To keep the database schema in step with your code, apply pending migrations every time the app runs.
Add a migration resource to your AppHost with AddEFMigrationsaddEFMigrationsAddEFMigrations from the 📦 Aspire.Hosting.EntityFrameworkCore package. This package is in preview. Call RunDatabaseUpdateOnStartrunDatabaseUpdateOnStartRunDatabaseUpdateOnStart to apply migrations when the AppHost starts, and make the app wait for the migrations to finish with WaitForCompletionwaitForCompletionWaitForCompletion:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');await api.withReference(catalogdb);
const migrations = await api.addEFMigrations('api-migrations');await migrations.runDatabaseUpdateOnStart();
await api.waitForCompletion(migrations);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var api = builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb);
var migrations = api.AddEFMigrations("api-migrations") .RunDatabaseUpdateOnStart();
api.WaitForCompletion(migrations);
builder.Build().Run();If you prefer to apply EF Core migrations from your own code, create a worker service project that calls MigrateAsync and then exits. Register the DbContext and the worker in the project’s Program.cs file:
var builder = Host.CreateApplicationBuilder(args);
builder.AddServiceDefaults();builder.AddNpgsqlDbContext<CatalogContext>("catalogdb");builder.Services.AddHostedService<Worker>();
builder.Build().Run();The worker applies the migrations inside an execution strategy, so EF Core retries them after a transient connection error. If the migrations fail, the worker sets a nonzero exit code. It then stops the app:
using Microsoft.EntityFrameworkCore;
public class Worker( IServiceProvider serviceProvider, IHostApplicationLifetime lifetime) : BackgroundService{ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
var strategy = context.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(() => context.Database.MigrateAsync(stoppingToken)); } catch { // The host exits with code 0 after a failed background service // unless you set the exit code yourself. Environment.ExitCode = 1; throw; } finally { lifetime.StopApplication(); } }}In the AppHost, add the worker project and make the app wait for it to finish:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const migrations = await builder.addDotnetProject('migrations', '../MigrationService/MigrationService.csproj') .withReference(catalogdb) .waitFor(catalogdb);
await builder.addDotnetProject('api', '../Api/Api.csproj') .withReference(catalogdb) .waitForCompletion(migrations);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var migrations = builder.AddDotnetProject("migrations", "../MigrationService/MigrationService.csproj") .WithReference(catalogdb) .WaitFor(catalogdb);
builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb) .WaitForCompletion(migrations);
builder.Build().Run();If the migrations fail, the worker exits with code 1, and the app doesn’t start because WaitForCompletion requires a successful exit. For a step-by-step tutorial that builds a migration service, see Apply EF Core migrations in Aspire.
Add a db:migrate script to the app’s package.json file that runs drizzle-kit migrate. Then add a second resource to your AppHost that runs this script, and make the app wait for it to finish. Add the resource with AddJavaScriptAppaddJavaScriptAppAddJavaScriptApp from the 📦 Aspire.Hosting.JavaScript package:
{ "scripts": { "db:migrate": "drizzle-kit migrate" }}import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' }) .withReference(catalogdb) .waitFor(catalogdb);
await builder.addNodeApp('api', './api', 'src/index.ts') .withReference(catalogdb) .waitForCompletion(migrate);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") .WithReference(catalogdb) .WaitFor(catalogdb);
builder.AddNodeApp("api", "../api", "src/index.ts") .WithReference(catalogdb) .WaitForCompletion(migrate);
builder.Build().Run();App paths are relative to the AppHost. The TypeScript example assumes that apphost.mts is in the same folder as the api folder. The C# example assumes that the AppHost is in its own project folder, next to the api folder. Adjust the paths to match your solution layout.
Point the Drizzle Kit configuration at the connection URI that Aspire passes to the resource:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({ dialect: 'postgresql', schema: './src/schema.ts', out: './drizzle', dbCredentials: { url: process.env.CATALOGDB_URI!, },});To apply Drizzle migrations from the app process instead, call the migrate function from drizzle-orm/node-postgres/migrator before the app starts handling requests. You don’t need the api-migrate resource with this approach:
import express from 'express';import { drizzle } from 'drizzle-orm/node-postgres';import { migrate } from 'drizzle-orm/node-postgres/migrator';
const db = drizzle(process.env.CATALOGDB_URI!);
// Apply pending migrations before the app accepts requests.await migrate(db, { migrationsFolder: './drizzle' });
const app = express();
// Add your routes...
app.listen(process.env.PORT);If you run more than one replica of the app, each replica applies the migrations when it starts. Use a separate migration resource when only one process should change the schema.
For more information about the JavaScript hosting APIs, see Customize scripts.
For more information about waiting for resources, see Health checks.
Modify a schema with a custom command
Section titled “Modify a schema with a custom command”Applying migrations on every run isn’t always what you want. For example, you might want to review a migration before you apply it, or apply it to a database that already holds data you care about. In these cases, apply the migrations on demand from a command in the dashboard.
When you add an EF Core migration resource without calling RunDatabaseUpdateOnStart, the resource doesn’t apply migrations on its own. It still appears in the dashboard, with commands that run the EF Core tools for that project. If your migrations are in a different project from the app, such as a data project, point the resource at that project with WithMigrationsProjectwithMigrationsProjectWithMigrationsProject:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');await api.withReference(catalogdb);
// No RunDatabaseUpdateOnStart call, so migrations run only from the dashboard.const migrations = await api.addEFMigrations('api-migrations');await migrations.withMigrationsProject({ migrationsProject: '../Data/Data.csproj' });
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var api = builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb);
// No RunDatabaseUpdateOnStart call, so migrations run only from the dashboard.api.AddEFMigrations("api-migrations") .WithMigrationsProject("../Data/Data.csproj");
builder.Build().Run();Pass the path to the migrations project, relative to the AppHost. If your migrations are in the app project, omit the call. For more information, see Automated EF migrations with AddEFMigrations.
You can also expose migrations as an endpoint in your app and call it with a custom HTTP command. Anyone who can reach the endpoint can change your schema, so the dashboard’s confirmation prompt isn’t enough protection on its own. Register the endpoint only in development, and require a shared secret that only the AppHost knows. The AppHost passes the secret to the app as an environment variable and sends it in a header when you run the command. For more information, see Considerations when registering HTTP commands.
The endpoint calls MigrateAsync on the database context. This example assumes that the app registers a DbContext named CatalogContext. For more information, see Use Aspire to create an EF Core context.
using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;
// After you build the app...
if (app.Environment.IsDevelopment()){ app.MapPost("/admin/migrate", async ( [FromHeader(Name = "X-Migration-Key")] string? key, IConfiguration config, CatalogContext context) => { if (config["MIGRATION_KEY"] is not { Length: > 0 } expected || key != expected) { return Results.Unauthorized(); }
await context.Database.MigrateAsync(); return Results.Ok(new { status = "Migrations applied" }); });}Then add the command to the app resource in your AppHost. The AppHost generates a random key each time it starts, passes it to the app in the MIGRATION_KEY environment variable, and adds it to the command’s request in the X-Migration-Key header:
import { randomBytes } from 'node:crypto';import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const migrationKey = randomBytes(32).toString('hex');
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api', '../Api/Api.csproj') .withReference(catalogdb) .waitFor(catalogdb) .withEnvironment('MIGRATION_KEY', migrationKey) .withHttpCommand('/admin/migrate', 'Apply migrations', { methodName: 'POST', confirmationMessage: 'Apply pending migrations to the catalog database?', prepareRequest: async () => ({ headers: { 'X-Migration-Key': migrationKey }, }), });
await builder.build().run();using System.Security.Cryptography;
var builder = DistributedApplication.CreateBuilder(args);
var migrationKey = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb) .WaitFor(catalogdb) .WithEnvironment("MIGRATION_KEY", migrationKey) .WithHttpCommand( path: "/admin/migrate", displayName: "Apply migrations", commandOptions: new HttpCommandOptions { Method = HttpMethod.Post, ConfirmationMessage = "Apply pending migrations to the catalog database?", PrepareRequest = context => { context.Request.Headers.Add("X-Migration-Key", migrationKey); return Task.CompletedTask; } });
builder.Build().Run();To apply migrations on demand, expose them as an endpoint in your app and call it with a custom HTTP command. Anyone who can reach the endpoint can change your schema, so the dashboard’s confirmation prompt isn’t enough protection on its own. Register the endpoint only in development, and require a shared secret that only the AppHost knows. The AppHost passes the secret to the app as an environment variable and sends it in a header when you run the command. For more information, see Considerations when registering HTTP commands.
The endpoint calls the migrate function:
import express from 'express';import { drizzle } from 'drizzle-orm/node-postgres';import { migrate } from 'drizzle-orm/node-postgres/migrator';
const app = express();const db = drizzle(process.env.CATALOGDB_URI!);const migrationKey = process.env.MIGRATION_KEY;
if (process.env.NODE_ENV === 'development' && migrationKey) { app.post('/admin/migrate', async (req, res) => { if (req.get('X-Migration-Key') !== migrationKey) { res.sendStatus(401); return; }
await migrate(db, { migrationsFolder: './drizzle' }); res.json({ status: 'Migrations applied' }); });}
// Add your other routes...
app.listen(process.env.PORT);Then add the command to the app resource in your AppHost. The AppHost generates a random key each time it starts, passes it to the app in the MIGRATION_KEY environment variable, and adds it to the command’s request in the X-Migration-Key header:
import { randomBytes } from 'node:crypto';import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const migrationKey = randomBytes(32).toString('hex');
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts') .withHttpEndpoint({ env: 'PORT' }) .withReference(catalogdb) .waitFor(catalogdb) .withEnvironment('MIGRATION_KEY', migrationKey) .withHttpCommand('/admin/migrate', 'Apply migrations', { methodName: 'POST', confirmationMessage: 'Apply pending migrations to the catalog database?', prepareRequest: async () => ({ headers: { 'X-Migration-Key': migrationKey }, }), });
await builder.build().run();using System.Security.Cryptography;
var builder = DistributedApplication.CreateBuilder(args);
var migrationKey = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddNodeApp("api", "../api", "src/index.ts") .WithHttpEndpoint(env: "PORT") .WithReference(catalogdb) .WaitFor(catalogdb) .WithEnvironment("MIGRATION_KEY", migrationKey) .WithHttpCommand( path: "/admin/migrate", displayName: "Apply migrations", commandOptions: new HttpCommandOptions { Method = HttpMethod.Post, ConfirmationMessage = "Apply pending migrations to the catalog database?", PrepareRequest = context => { context.Request.Headers.Add("X-Migration-Key", migrationKey); return Task.CompletedTask; } });
builder.Build().Run();The HTTP endpoint passes its port to the app in the PORT environment variable. The app must listen on process.env.PORT, otherwise the command can’t reach it.
Dashboard commands are available only when you run the dashboard locally. Don’t rely on them to migrate a deployed database. For deployment options, see Deploy a database with an Aspire solution.
For more information, see Custom HTTP commands and Custom resource commands.
Modify a schema in a dashboard REPL terminal
Section titled “Modify a schema in a dashboard REPL terminal”You can also change a schema by hand. Open the database’s REPL from the dashboard, as described in Create a database in a dashboard REPL terminal, and run statements such as ALTER TABLE. This approach is useful when you experiment with a schema change before you write a migration for it.
Persist a database across restarts
Section titled “Persist a database across restarts”By default, Aspire removes a database container when the AppHost stops, so the database and its data are lost. To keep the data between runs, store it outside the container:
- Call
WithDataVolumewithDataVolumeWithDataVolumeto store the data in a volume that the container runtime manages. Use a volume in most cases. - Call
WithDataBindMountwithDataBindMountWithDataBindMountto store the data in a folder on your machine. Use a bind mount when you need to open the data files directly.
To also keep the container itself running between runs, call WithPersistentLifetimewithPersistentLifetimeWithPersistentLifetime. A persistent container makes the AppHost start faster, but it doesn’t protect your data on its own. If the container is recreated, for example after a configuration change, its data is lost unless it’s stored in a volume. For databases, use a data volume and a persistent lifetime together:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');await postgres.withDataVolume();await postgres.withPersistentLifetime();
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.build().run();#pragma warning disable ASPIREPERSISTENCE001
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres") .WithDataVolume() .WithPersistentLifetime();
var catalogdb = postgres.AddDatabase("catalogdb");
builder.Build().Run();In a C# AppHost, the persistent lifetime API is experimental and requires suppressing the ASPIREPERSISTENCE001 diagnostic.
When the data persists, plan how seed logic and initialization scripts behave on later runs. Initialization scripts run only against an empty data directory, and seed code should check for existing rows. Aspire generates the password on first run and stores it in the AppHost’s user secrets. Set it yourself if you want to control or share it.
For more information, see Persist Aspire data with volumes and binds, Create persistent passwords, and Container lifetime vs. data durability.
Deploy a database with an Aspire solution
Section titled “Deploy a database with an Aspire solution”When you deploy, the database resources in your AppHost become part of the deployment. You choose between two models:
- Deploy the database as a container next to your app. The deployment target, such as Docker Compose, Kubernetes, or Azure Container Apps, runs the same database image that you use in development. Without a volume, the container starts with a new, empty database each time it’s replaced, so attach a volume to keep the data between deployments.
- Use a managed database service, such as Azure Database for PostgreSQL or Azure SQL Database. The cloud provider stores the data, so it stays in place across deployments. Aspire creates the databases in your AppHost during the first deployment and doesn’t recreate or delete them later.
To use a managed service when you deploy and a local container during development, call RunAsContainer on the Azure resource. This example uses the 📦 Aspire.Hosting.Azure.PostgreSQL package:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addAzurePostgresFlexibleServer('postgres');await postgres.runAsContainer();
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addDotnetProject('api', '../Api/Api.csproj') .withReference(catalogdb) .waitFor(catalogdb);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddAzurePostgresFlexibleServer("postgres") .RunAsContainer();
var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb) .WaitFor(catalogdb);
builder.Build().Run();import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addAzurePostgresFlexibleServer('postgres');await postgres.runAsContainer();
const catalogdb = await postgres.addDatabase('catalogdb');
await builder.addNodeApp('api', './api', 'src/index.ts') .withReference(catalogdb) .waitFor(catalogdb);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddAzurePostgresFlexibleServer("postgres") .RunAsContainer();
var catalogdb = postgres.AddDatabase("catalogdb");
builder.AddNodeApp("api", "../api", "src/index.ts") .WithReference(catalogdb) .WaitFor(catalogdb);
builder.Build().Run();When you run the app locally, Aspire starts a PostgreSQL container. When you deploy, it provisions Azure Database for PostgreSQL.
Your schema must also reach the deployed database, so plan how your migrations run when you deploy.
RunDatabaseUpdateOnStart affects only local runs. To apply migrations in a deployed environment, publish them as a container image with PublishAsMigrationBundlepublishAsMigrationBundlePublishAsMigrationBundle. The bundle is deployed with your app and applies pending migrations when it runs. If you want to review the SQL before it runs, call PublishAsMigrationScriptpublishAsMigrationScriptPublishAsMigrationScript instead. It generates an idempotent SQL script during aspire publish, which you then run against the database yourself.
A migration bundle container exits after it applies the migrations. Configure each deployment target so that it doesn’t restart the container:
- On Azure Container Apps, publish the migration resource as a job with
PublishAsAzureContainerAppJobpublishAsAzureContainerAppJobPublishAsAzureContainerAppJob. A manually triggered job doesn’t run until you start it. To start it during deployment, see Ensure successful migrations deployment. - On Docker Compose, set the service’s restart policy to
nowithPublishAsDockerComposeServicepublishAsDockerComposeServicePublishAsDockerComposeService, as shown in the following example. - On Kubernetes, customize the generated manifest to use a
Jobworkload, or setrestartPolicy: OnFailure.
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addDockerComposeEnvironment('compose');
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');await api.withReference(catalogdb);
const migrations = await api.addEFMigrations('api-migrations');await migrations.withReference(catalogdb);await migrations.waitFor(catalogdb);await migrations.publishAsMigrationBundle({ publishContainer: true });await migrations.publishAsDockerComposeService(async (resource, service) => { await service.restart.set('no');});
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
builder.AddDockerComposeEnvironment("compose");
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var api = builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb);
api.AddEFMigrations("api-migrations") .WithReference(catalogdb) .WaitFor(catalogdb) .PublishAsMigrationBundle(publishContainer: true) .PublishAsDockerComposeService((_, service) => service.Restart = "no");
builder.Build().Run();The Docker Compose methods come from the 📦 Aspire.Hosting.Docker package. Call WithReference on the migration resource so that the bundle container receives the database connection string, and WaitFor so that Docker Compose starts it after the database container. Docker Compose waits for the container to start, not for the database to accept connections.
Run drizzle-kit migrate as a step in your CI/CD pipeline, or call the migrate function when the deployed app starts, as shown in Apply schema migrations on startup. To deploy the api-migrate resource from that section instead, call PublishAsPackageScriptpublishAsPackageScriptPublishAsPackageScript. The deployment then builds a container image that runs the db:migrate script. For other publishing options, see Deploy JavaScript apps.
The generated Dockerfile installs packages with npm ci and then runs npm run build, so the app needs a package-lock.json file and a build script. The app in these examples runs its TypeScript source directly with Node.js, so its build script only needs to succeed:
{ "scripts": { "build": "echo \"No build step\"", "db:migrate": "drizzle-kit migrate" }}If your app’s build step uses another script name, select that script when you add the resource. For more information, see Customize scripts.
The api-migrate container exits after it applies the migrations. Configure each deployment target so that it doesn’t restart the container:
- On Azure Container Apps, publish the migration resource as a job with
PublishAsAzureContainerAppJobpublishAsAzureContainerAppJobPublishAsAzureContainerAppJob. A manually triggered job doesn’t run until you start it. To start it during deployment, see Ensure successful migrations deployment. - On Docker Compose, set the service’s restart policy to
nowithPublishAsDockerComposeServicepublishAsDockerComposeServicePublishAsDockerComposeService, as shown in the following example. - On Kubernetes, customize the generated manifest to use a
Jobworkload, or setrestartPolicy: OnFailure.
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
await builder.addDockerComposeEnvironment('compose');
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' }) .withReference(catalogdb) .waitFor(catalogdb) .publishAsPackageScript({ scriptName: 'db:migrate' });await migrate.publishAsDockerComposeService(async (resource, service) => { await service.restart.set('no');});
await builder.addNodeApp('api', './api', 'src/index.ts') .withReference(catalogdb) .waitForCompletion(migrate);
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
builder.AddDockerComposeEnvironment("compose");
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") .WithReference(catalogdb) .WaitFor(catalogdb) .PublishAsPackageScript(scriptName: "db:migrate") .PublishAsDockerComposeService((_, service) => service.Restart = "no");
builder.AddNodeApp("api", "../api", "src/index.ts") .WithReference(catalogdb) .WaitForCompletion(migrate);
builder.Build().Run();The Docker Compose methods come from the 📦 Aspire.Hosting.Docker package. The db:migrate script runs drizzle-kit in the container, so list drizzle-kit under dependencies in package.json, not devDependencies. A production image doesn’t have to include development dependencies.
Don’t deploy development seed data or seed endpoints. Seed data that’s part of your migrations, such as reference data, is deployed with the migrations.
For more information, see Deploy with Aspire, Persistent volumes on Kubernetes, Run as a local container during development, and Database creation after initial deployment.
Ensure successful migrations deployment
Section titled “Ensure successful migrations deployment”When you deploy a new version of your app, the new code often expects the new schema. If the app starts before the migrations finish, or if the migrations fail, the app can fail at runtime. To prevent this, make the deployment apply migrations first, and stop it when they fail. Choose one of these approaches:
- Add a custom step to the Aspire deployment pipeline so that
aspire deployruns a migration job and waits for it to succeed before it updates the app. - Run an EF Core migration bundle in your CI/CD pipeline before you call
aspire deploy.
- Add a custom step to the Aspire deployment pipeline so that
aspire deployruns a migration job and waits for it to succeed before it updates the app. - Run
drizzle-kit migratein your CI/CD pipeline before you callaspire deploy.
Either way, the app version that’s still running keeps serving requests while the migrations run. Write migrations that the old version of the app can tolerate. For example, add a column in one release and remove the old column in a later release.
Run migrations in the deployment pipeline
Section titled “Run migrations in the deployment pipeline”The aspire deploy command runs a pipeline of named steps, such as provision-api-containerapp and deploy-api. You can add your own steps to this pipeline and declare which steps must run before and after them. To make the app deployment wait for the migrations, deploy the migrations as a job and add a step that:
- Runs after the step that creates or updates the migration job.
- Starts the job and waits for it to finish. If the job fails, the step throws an error, and the pipeline stops.
- Runs before the step that updates the app, so that the app is updated only after the migrations succeed.
The following examples deploy to Azure Container Apps, so they need the 📦 Aspire.Hosting.Azure.AppContainers package. Aspire creates or updates each container app or job in a step named provision-<resource-name>-containerapp. A manually triggered job doesn’t run when it’s deployed, so the custom step starts it with the az containerapp job start command and polls its status. To find the step names for your deployment target, run aspire do diagnostics, which prints the dependency graph of the pipeline.
Aspire creates the Azure deployment steps while it resolves the pipeline, after your AppHost code adds its own steps. To depend on an Azure step reliably, add your step without dependencies, then add the dependencies in a pipeline configuration callback. Aspire runs this callback after all the steps exist. The callback also runs during pipeline passes that don’t create the Azure steps, so it adds the dependencies only when it finds them.
Publish the migration bundle as a container image and deploy it as a manually triggered job with PublishAsAzureContainerAppJobpublishAsAzureContainerAppJobPublishAsAzureContainerAppJob. Then add the custom step and the configuration callback. In C#, use builder.Pipeline.AddStep and builder.Pipeline.AddPipelineConfiguration. In TypeScript, use pipeline.addStep and pipeline.configure:
import { execFile } from 'node:child_process';import { setTimeout as delay } from 'node:timers/promises';import { promisify } from 'node:util';import { createBuilder } from './.aspire/modules/aspire.mjs';
const run = promisify(execFile);
const builder = await createBuilder();
await builder.addAzureContainerAppEnvironment('env');
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');await api.withReference(catalogdb);
// Deploy the migration bundle as a manually triggered job.const migrations = await api.addEFMigrations('api-migrations');await migrations.withReference(catalogdb);await migrations.waitFor(catalogdb);await migrations.publishAsMigrationBundle({ publishContainer: true });await migrations.publishAsAzureContainerAppJob();
if (await builder.executionContext().isPublishMode()) { const pipeline = await builder.pipeline();
await pipeline.addStep('run-api-migrations', async (context) => { const logger = await context.logger(); const resourceGroup = process.env.Azure__ResourceGroup!; const job = ['--name', 'api-migrations', '--resource-group', resourceGroup];
const { stdout } = await run('az', [ 'containerapp', 'job', 'start', ...job, '--query', 'name', '--output', 'tsv', ]); const execution = stdout.trim(); await logger.logInformation(`Started migration job execution ${execution}.`);
while (true) { await delay(10_000); const { stdout: output } = await run('az', [ 'containerapp', 'job', 'execution', 'show', ...job, '--job-execution-name', execution, '--query', 'properties.status', '--output', 'tsv', ]); const status = output.trim();
if (status === 'Succeeded') { await logger.logInformation('Migrations applied.'); return; }
if (['Failed', 'Stopped', 'Degraded'].includes(status)) { throw new Error(`Migration job execution ${execution} ended with status ${status}.`); } } });
// Azure creates its deployment steps while the pipeline resolves, // so add the dependencies in a configuration callback. await pipeline.configure(async (context) => { const steps = new Map(); for (const step of await (await context.pipeline()).steps()) { steps.set(await step.name(), step); }
const deployApp = steps.get('provision-api-containerapp'); if (steps.has('provision-api-migrations-containerapp') && deployApp) { // Run after the migration job is created or updated, await steps.get('run-api-migrations').dependsOn('provision-api-migrations-containerapp'); // and before the app is updated. await deployApp.dependsOn('run-api-migrations'); } });}
await builder.build().run();using System.Diagnostics;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureContainerAppEnvironment("env");
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var api = builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb);
// Deploy the migration bundle as a manually triggered job.api.AddEFMigrations("api-migrations") .WithReference(catalogdb) .WaitFor(catalogdb) .PublishAsMigrationBundle(publishContainer: true) .PublishAsAzureContainerAppJob();
if (builder.ExecutionContext.IsPublishMode){ builder.Pipeline.AddStep("run-api-migrations", async context => { var config = context.Services.GetRequiredService<IConfiguration>(); string[] job = ["--name", "api-migrations", "--resource-group", config["Azure:ResourceGroup"]!];
string[] startArgs = ["containerapp", "job", "start", .. job, "--query", "name", "--output", "tsv"]; var execution = await RunAzAsync(startArgs, context.CancellationToken); context.Logger.LogInformation("Started migration job execution {Execution}.", execution);
string[] showArgs = [ "containerapp", "job", "execution", "show", .. job, "--job-execution-name", execution, "--query", "properties.status", "--output", "tsv" ];
while (true) { await Task.Delay(TimeSpan.FromSeconds(10), context.CancellationToken); var status = await RunAzAsync(showArgs, context.CancellationToken);
if (status == "Succeeded") { context.Logger.LogInformation("Migrations applied."); return; }
if (status is "Failed" or "Stopped" or "Degraded") { throw new InvalidOperationException( $"Migration job execution {execution} ended with status {status}."); } } });
// Azure creates its deployment steps while the pipeline resolves, // so add the dependencies in a configuration callback. builder.Pipeline.AddPipelineConfiguration(context => { var runMigrations = context.Steps.Single(s => s.Name == "run-api-migrations"); var deployJob = context.Steps.SingleOrDefault(s => s.Name == "provision-api-migrations-containerapp"); var deployApp = context.Steps.SingleOrDefault(s => s.Name == "provision-api-containerapp");
if (deployJob is not null && deployApp is not null) { // Run after the migration job is created or updated, runMigrations.DependsOn(deployJob); // and before the app is updated. deployApp.DependsOn(runMigrations); }
return Task.CompletedTask; });}
builder.Build().Run();
static async Task<string> RunAzAsync(string[] args, CancellationToken cancellationToken){ var startInfo = new ProcessStartInfo("az") { RedirectStandardOutput = true }; foreach (var arg in args) { startInfo.ArgumentList.Add(arg); }
using var process = Process.Start(startInfo)!; var output = await process.StandardOutput.ReadToEndAsync(cancellationToken); await process.WaitForExitAsync(cancellationToken);
if (process.ExitCode != 0) { throw new InvalidOperationException($"'az {string.Join(' ', args)}' failed."); }
return output.Trim();}Deploy the db:migrate script from Apply schema migrations on startup as a job. Call PublishAsPackageScript to build a container image that runs the script, and deploy the image as a manually triggered job. Then add the custom step and the configuration callback for the api-migrate job. In C#, use builder.Pipeline.AddStep and builder.Pipeline.AddPipelineConfiguration. In TypeScript, use pipeline.addStep and pipeline.configure:
import { execFile } from 'node:child_process';import { setTimeout as delay } from 'node:timers/promises';import { promisify } from 'node:util';import { createBuilder } from './.aspire/modules/aspire.mjs';
const run = promisify(execFile);
const builder = await createBuilder();
await builder.addAzureContainerAppEnvironment('env');
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
// Deploy the db:migrate script as a manually triggered job.const migrate = await builder.addJavaScriptApp('api-migrate', './api', { runScriptName: 'db:migrate' }) .withReference(catalogdb) .waitFor(catalogdb) .publishAsPackageScript({ scriptName: 'db:migrate' });await migrate.publishAsAzureContainerAppJob();
await builder.addNodeApp('api', './api', 'src/index.ts') .withReference(catalogdb) .waitForCompletion(migrate);
if (await builder.executionContext().isPublishMode()) { const pipeline = await builder.pipeline();
await pipeline.addStep('run-api-migrations', async (context) => { const logger = await context.logger(); const resourceGroup = process.env.Azure__ResourceGroup!; const job = ['--name', 'api-migrate', '--resource-group', resourceGroup];
const { stdout } = await run('az', [ 'containerapp', 'job', 'start', ...job, '--query', 'name', '--output', 'tsv', ]); const execution = stdout.trim(); await logger.logInformation(`Started migration job execution ${execution}.`);
while (true) { await delay(10_000); const { stdout: output } = await run('az', [ 'containerapp', 'job', 'execution', 'show', ...job, '--job-execution-name', execution, '--query', 'properties.status', '--output', 'tsv', ]); const status = output.trim();
if (status === 'Succeeded') { await logger.logInformation('Migrations applied.'); return; }
if (['Failed', 'Stopped', 'Degraded'].includes(status)) { throw new Error(`Migration job execution ${execution} ended with status ${status}.`); } } });
// Azure creates its deployment steps while the pipeline resolves, // so add the dependencies in a configuration callback. await pipeline.configure(async (context) => { const steps = new Map(); for (const step of await (await context.pipeline()).steps()) { steps.set(await step.name(), step); }
const deployApp = steps.get('provision-api-containerapp'); if (steps.has('provision-api-migrate-containerapp') && deployApp) { // Run after the migration job is created or updated, await steps.get('run-api-migrations').dependsOn('provision-api-migrate-containerapp'); // and before the app is updated. await deployApp.dependsOn('run-api-migrations'); } });}
await builder.build().run();using System.Diagnostics;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureContainerAppEnvironment("env");
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
// Deploy the db:migrate script as a manually triggered job.var migrate = builder.AddJavaScriptApp("api-migrate", "../api", "db:migrate") .WithReference(catalogdb) .WaitFor(catalogdb) .PublishAsPackageScript(scriptName: "db:migrate") .PublishAsAzureContainerAppJob();
builder.AddNodeApp("api", "../api", "src/index.ts") .WithReference(catalogdb) .WaitForCompletion(migrate);
if (builder.ExecutionContext.IsPublishMode){ builder.Pipeline.AddStep("run-api-migrations", async context => { var config = context.Services.GetRequiredService<IConfiguration>(); string[] job = ["--name", "api-migrate", "--resource-group", config["Azure:ResourceGroup"]!];
string[] startArgs = ["containerapp", "job", "start", .. job, "--query", "name", "--output", "tsv"]; var execution = await RunAzAsync(startArgs, context.CancellationToken); context.Logger.LogInformation("Started migration job execution {Execution}.", execution);
string[] showArgs = [ "containerapp", "job", "execution", "show", .. job, "--job-execution-name", execution, "--query", "properties.status", "--output", "tsv" ];
while (true) { await Task.Delay(TimeSpan.FromSeconds(10), context.CancellationToken); var status = await RunAzAsync(showArgs, context.CancellationToken);
if (status == "Succeeded") { context.Logger.LogInformation("Migrations applied."); return; }
if (status is "Failed" or "Stopped" or "Degraded") { throw new InvalidOperationException( $"Migration job execution {execution} ended with status {status}."); } } });
// Azure creates its deployment steps while the pipeline resolves, // so add the dependencies in a configuration callback. builder.Pipeline.AddPipelineConfiguration(context => { var runMigrations = context.Steps.Single(s => s.Name == "run-api-migrations"); var deployJob = context.Steps.SingleOrDefault(s => s.Name == "provision-api-migrate-containerapp"); var deployApp = context.Steps.SingleOrDefault(s => s.Name == "provision-api-containerapp");
if (deployJob is not null && deployApp is not null) { // Run after the migration job is created or updated, runMigrations.DependsOn(deployJob); // and before the app is updated. deployApp.DependsOn(runMigrations); }
return Task.CompletedTask; });}
builder.Build().Run();
static async Task<string> RunAzAsync(string[] args, CancellationToken cancellationToken){ var startInfo = new ProcessStartInfo("az") { RedirectStandardOutput = true }; foreach (var arg in args) { startInfo.ArgumentList.Add(arg); }
using var process = Process.Start(startInfo)!; var output = await process.StandardOutput.ReadToEndAsync(cancellationToken); await process.WaitForExitAsync(cancellationToken);
if (process.ExitCode != 0) { throw new InvalidOperationException($"'az {string.Join(' ', args)}' failed."); }
return output.Trim();}The db:migrate script runs drizzle-kit in the container, so list drizzle-kit under dependencies in package.json, not devDependencies. A production image doesn’t have to include development dependencies.
The custom step reads the resource group from the Azure__ResourceGroup environment variable, so set it when you run aspire deploy. The Azure CLI must be installed and signed in to the same subscription. On Windows, run az.cmd instead of az.
You can use the same pattern with other deployment targets. Replace the az commands with the commands that run a one-off job on your target, such as docker compose run or kubectl wait --for=condition=complete. Then depend on the steps that your target adds to the pipeline.
For more information, see Pipelines and app topology, Azure Container Apps jobs, and Jobs in Azure Container Apps in the Azure documentation.
Run migrations as a CI/CD pre-deployment step
Section titled “Run migrations as a CI/CD pre-deployment step”To apply migrations before the app is deployed, run them from your CI/CD pipeline before you call aspire deploy. If they fail, the pipeline stops before the deployment starts.
An EF Core migration bundle is a single executable that applies your migrations to a database. It doesn’t need the .NET SDK or your source code, so you can run it from a CI/CD pipeline before you deploy.
To generate the bundle, publish the migration resource as a migration bundle. Set the target runtime to match your CI/CD agent, and make the bundle self-contained so that the agent doesn’t need the .NET runtime:
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const postgres = await builder.addPostgres('postgres');const catalogdb = await postgres.addDatabase('catalogdb');
const api = await builder.addDotnetProject('api', '../Api/Api.csproj');await api.withReference(catalogdb);
await api.addEFMigrations('api-migrations') .publishAsMigrationBundle({ targetRuntime: 'linux-x64', selfContained: true });
await builder.build().run();var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");var catalogdb = postgres.AddDatabase("catalogdb");
var api = builder.AddDotnetProject("api", "../Api/Api.csproj") .WithReference(catalogdb);
api.AddEFMigrations("api-migrations") .PublishAsMigrationBundle(targetRuntime: "linux-x64", selfContained: true);
builder.Build().Run();A pipeline step named <resource-name>-generate-migration-bundle generates the bundle and writes it to the efmigrations folder in the publish output. In your CI/CD pipeline, run that step on its own, run the bundle against the production database, and then deploy:
# Generate the bundle at ./artifacts/efmigrations/api-migrations.aspire do api-migrations-generate-migration-bundle --output-path ./artifacts
# Apply pending migrations. The command fails if any migration fails../artifacts/efmigrations/api-migrations --connection "$CATALOGDB_CONNECTION_STRING"
# Deploy the app only after the migrations succeed.aspire deployStore the connection string in your CI/CD system’s secret store, and make sure the agent can reach the database through its firewall. The step that generates the bundle doesn’t deploy anything. You can run it in a build stage and pass the bundle to a later deployment stage as an artifact.
For more information, see Migration bundles in the EF Core documentation and the aspire do command.
Drizzle has no equivalent of an EF Core migration bundle. Instead, run drizzle-kit migrate in your CI/CD pipeline with the production connection string. The drizzle.config.ts file from Apply schema migrations on startup reads the connection string from the CATALOGDB_URI environment variable:
# Apply pending migrations from the app folder. The command fails if any migration fails.(cd api && CATALOGDB_URI="$CATALOGDB_CONNECTION_STRING" npx drizzle-kit migrate)
# Deploy the app only after the migrations succeed.aspire deployStore the connection string in your CI/CD system’s secret store, and make sure the agent can reach the database through its firewall.