# 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:

<PivotSelector
    title="Select your ORM"
    key="orm"
    options={[
        { id: "efcore", title: "EF Core" },
        { id: "drizzle", title: "Drizzle" },
    ]}
/>

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](#create-a-database-in-the-apphost) |
| | In an orchestrated app | [On startup or with a custom command](#create-a-database-in-an-orchestrated-app) |
| | In a dashboard <abbr title="Read-eval-print loop">REPL</abbr> terminal | [Run commands or a script](#create-a-database-in-a-dashboard-repl-terminal) |
| Seed a database | In an orchestrated app | [On startup or with a custom command](#seed-a-database-on-startup-or-using-a-custom-command) |
| | | [Use EF Core or Drizzle migrations](#seed-a-database-using-orm-migrations) |
| | In a dashboard REPL terminal | [Run a script](#seed-a-database-in-a-dashboard-repl-terminal) |
| Modify a database schema | In an orchestrated app | [Apply migrations on startup](#apply-schema-migrations-on-startup) |
| | | [Apply migrations with a custom command](#modify-a-schema-with-a-custom-command) |
| | In a dashboard REPL terminal | [Run a script](#modify-a-schema-in-a-dashboard-repl-terminal) |
| Persist a database across restarts | In the AppHost | [Data volumes, bind mounts, and persistent lifetimes](#persist-a-database-across-restarts) |
| Deploy a database | In the AppHost | [A container database or a managed database service](#deploy-a-database-with-an-aspire-solution) |

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

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

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](https://www.nuget.org/packages/Aspire.Hosting.PostgreSQL) package. Call <ApiReference name="Aspire.Hosting.PostgresBuilderExtensions.AddDatabase" /> on the server resource, then reference the database from the app that uses it:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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. <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WithReference" /> passes the database's connection information to the app, and <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WaitFor" /> 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 <ApiReference name="Aspire.Hosting.PostgresBuilderExtensions.WithCreationScript" />. SQL Server and MySQL support the same method.

<LearnMore>
  For more information, see [Add PostgreSQL resource with database scripts](/integrations/databases/postgres/postgres-host/#add-postgresql-resource-with-database-scripts). For details on how Aspire waits for the server to be ready, see [AppHost eventing APIs](/app-host/eventing/).
</LearnMore>

### 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.

<Pivot id="efcore">

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`:

```csharp title="Program.cs"
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();
```

</Pivot>

<Pivot id="drizzle">

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:

```typescript title="src/create-database.ts"
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](#seed-a-database-on-startup-or-using-a-custom-command) section shows both approaches.

</Pivot>

<LearnMore>
  For the environment variables that Aspire passes to apps for each resource, see [Connect to PostgreSQL](/integrations/databases/postgres/postgres-connect/).
</LearnMore>

### 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 <ApiReference name="Aspire.Hosting.PostgresBuilderExtensions.WithRepl" /> 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:

```typescript title="apphost.mts"
import { createBuilder } from './.aspire/modules/aspire.mjs';

const builder = await createBuilder();

await builder.addPostgres('postgres').withRepl();

await builder.build().run();
```

```csharp title="AppHost.cs"
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:

```sql title="psql"
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](#persist-a-database-across-restarts).

:::caution
The REPL uses the resource's credentials and can modify or delete any data. Enable it only for trusted dashboard users.
:::

<LearnMore>
  For more information, see [Open a database or cache REPL](/dashboard/ephemeral-terminals/#open-a-database-or-cache-repl). For an overview of all terminal types, see [Use interactive terminals in the dashboard](/dashboard/terminals/).
</LearnMore>

## 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

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

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.

<Pivot id="efcore">

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:

```csharp title="Program.cs"
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](/integrations/databases/efcore/seed-database/#seed-data-using-ef-core).

</Pivot>

<Pivot id="drizzle">

The `drizzle-seed` package generates realistic random data from your schema. The following example seeds the `products` table only when it's empty:

```typescript title="src/seed.ts"
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`.

</Pivot>

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.

<Pivot id="efcore">

The endpoint adds the rows through the database context. It checks for existing rows first, so you can run the command more than once:

```csharp title="Program.cs"
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 <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WithHttpCommand" />:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
```

</Pivot>

<Pivot id="drizzle">

The endpoint calls the `seedDatabase` function from the previous example:

```typescript title="api/src/index.ts"
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 <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WithHttpCommand" />:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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.

</Pivot>

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](#modify-a-schema-with-a-custom-command) show how to send a shared secret with each request.

<LearnMore>
  For more information, see [Custom HTTP commands](/fundamentals/http-commands/). To run logic in the AppHost itself instead of calling an endpoint, see [Custom resource commands](/fundamentals/custom-resource-commands/).
</LearnMore>

#### 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.

<Pivot id="efcore">

Call `HasData` in `OnModelCreating` to define seed rows as part of your model. Each row needs a primary key value:

```csharp title="CatalogContext.cs"
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:

```bash title="Terminal"
dotnet ef migrations add SeedOrderStatuses
```

EF 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](https://learn.microsoft.com/ef/core/modeling/data-seeding#model-managed-data) in the EF Core documentation.

</Pivot>

<Pivot id="drizzle">

Generate an empty custom migration:

```bash title="Terminal"
npx drizzle-kit generate --custom --name=seed-order-statuses
```

Drizzle Kit creates a SQL file in your migrations folder. Add your `INSERT` statements to that file:

```sql title="api/drizzle/0001_seed-order-statuses.sql"
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](https://orm.drizzle.team/docs/kit-custom-migrations) in the Drizzle documentation.

</Pivot>

To learn how to apply migrations when your app runs, see [Modify a database schema](#modify-a-database-schema).

### 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](#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 <ApiReference name="Aspire.Hosting.PostgresBuilderExtensions.WithInitFiles" />:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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:

```sql title="postgres-init/01-catalog.sql"
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](#persist-a-database-across-restarts) 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 <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WithExplicitStart" /> 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.

<Pivot id="efcore">

This example adds a .NET console project that seeds the database. The project registers the `DbContext` in the same way as the app:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
```

</Pivot>

<Pivot id="drizzle">

This example runs a `db:seed` script from the app's _package.json_ file:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
```

</Pivot>

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](/fundamentals/custom-resource-commands/#process-backed-resource-commands).

<LearnMore>
  For initialization script examples for SQL Server and MySQL, see [Seed data using SQL scripts](/integrations/databases/efcore/seed-database/#seed-data-using-sql-scripts).
</LearnMore>

## 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.

<Pivot id="efcore">

Run `dotnet ef migrations add <name>` to generate a C# migration from changes to your `DbContext` model. For more information, see [Create migrations](/integrations/databases/efcore/migrations/#create-migrations).

</Pivot>

<Pivot id="drizzle">

Run `npx drizzle-kit generate` to generate a SQL migration from changes to your schema file. For more information, see [Migrations with Drizzle](https://orm.drizzle.team/docs/migrations) in the Drizzle documentation.

</Pivot>

### Apply schema migrations on startup

To keep the database schema in step with your code, apply pending migrations every time the app runs.

<Pivot id="efcore">

Add a migration resource to your AppHost with <ApiReference name="Aspire.Hosting.EFResourceBuilderExtensions.AddEFMigrations" /> from the [📦 Aspire.Hosting.EntityFrameworkCore](https://www.nuget.org/packages/Aspire.Hosting.EntityFrameworkCore) package. This package is in preview. Call <ApiReference name="Aspire.Hosting.EFMigrationResourceBuilderExtensions.RunDatabaseUpdateOnStart" /> to apply migrations when the AppHost starts, and make the app wait for the migrations to finish with <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WaitForCompletion" />:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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:

```csharp title="MigrationService/Program.cs"
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:

```csharp title="MigrationService/Worker.cs"
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:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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](/integrations/databases/efcore/migrations/#create-the-migration-service).

</Pivot>

<Pivot id="drizzle">

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 <ApiReference name="Aspire.Hosting.JavaScriptHostingExtensions.AddJavaScriptApp" /> from the [📦 Aspire.Hosting.JavaScript](https://www.nuget.org/packages/Aspire.Hosting.JavaScript) package:

```json title="api/package.json"
{
  "scripts": {
    "db:migrate": "drizzle-kit migrate"
  }
}
```

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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:

```typescript title="api/drizzle.config.ts"
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:

```typescript title="api/src/index.ts"
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.

<LearnMore>
  For more information about the JavaScript hosting APIs, see [Customize scripts](/integrations/frameworks/javascript/#customize-scripts).
</LearnMore>

</Pivot>

<LearnMore>
  For more information about waiting for resources, see [Health checks](/fundamentals/health-checks/).
</LearnMore>

### 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.

<Pivot id="efcore">

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 <ApiReference name="Aspire.Hosting.EFMigrationResourceBuilderExtensions.WithMigrationsProject" />:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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`](/integrations/databases/efcore/migrations/#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](/fundamentals/http-commands/#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](/integrations/databases/efcore/overview/#use-aspire-to-create-an-ef-core-context).

```csharp title="Program.cs"
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:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
```

</Pivot>

<Pivot id="drizzle">

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](/fundamentals/http-commands/#considerations-when-registering-http-commands).

The endpoint calls the `migrate` function:

```typescript title="api/src/index.ts"
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:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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.

</Pivot>

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](#deploy-a-database-with-an-aspire-solution).

<LearnMore>
  For more information, see [Custom HTTP commands](/fundamentals/http-commands/) and [Custom resource commands](/fundamentals/custom-resource-commands/).
</LearnMore>

### 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](#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.

:::caution
An ORM doesn't know about changes that you make by hand. If you use migrations, a manual change can make the database differ from what the ORM expects, and later migrations can fail. Capture every change that you want to keep in a migration.
:::

## 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 <ApiReference name="Aspire.Hosting.PostgresBuilderExtensions.WithDataVolume" /> to store the data in a volume that the container runtime manages. Use a volume in most cases.
- Call <ApiReference name="Aspire.Hosting.PostgresBuilderExtensions.WithDataBindMount" /> to 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 <ApiReference name="Aspire.Hosting.ResourceBuilderExtensions.WithPersistentLifetime" />. 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:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
#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`](/diagnostics/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.

<LearnMore>
  For more information, see [Persist Aspire data with volumes and binds](/fundamentals/persist-data-volumes/), [Create persistent passwords](/fundamentals/persist-data-volumes/#create-persistent-passwords), and [Container lifetime vs. data durability](/app-host/resource-lifetimes/#container-lifetime-vs-data-durability).
</LearnMore>

## 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](https://www.nuget.org/packages/Aspire.Hosting.Azure.PostgreSQL) package:

<Pivot id="efcore">

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
```

</Pivot>

<Pivot id="drizzle">

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
```

</Pivot>

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.

<Pivot id="efcore">

`RunDatabaseUpdateOnStart` affects only local runs. To apply migrations in a deployed environment, publish them as a container image with <ApiReference name="Aspire.Hosting.EFMigrationResourceBuilderExtensions.PublishAsMigrationBundle" />. 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 <ApiReference name="Aspire.Hosting.EFMigrationResourceBuilderExtensions.PublishAsMigrationScript" /> 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 <ApiReference name="Aspire.Hosting.ContainerAppExtensions.PublishAsAzureContainerAppJob" />. A manually triggered job doesn't run until you start it. To start it during deployment, see [Ensure successful migrations deployment](#ensure-successful-migrations-deployment).
- On Docker Compose, set the service's restart policy to `no` with <ApiReference name="Aspire.Hosting.DockerComposeServiceExtensions.PublishAsDockerComposeService" />, as shown in the following example.
- On Kubernetes, customize the generated manifest to use a `Job` workload, or set `restartPolicy: OnFailure`.

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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](https://www.nuget.org/packages/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.

</Pivot>

<Pivot id="drizzle">

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](#apply-schema-migrations-on-startup). To deploy the `api-migrate` resource from that section instead, call <ApiReference name="Aspire.Hosting.JavaScriptHostingExtensions.PublishAsPackageScript" />. The deployment then builds a container image that runs the `db:migrate` script. For other publishing options, see [Deploy JavaScript apps](/deployment/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:

```json title="api/package.json"
{
  "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](/integrations/frameworks/javascript/#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 <ApiReference name="Aspire.Hosting.ContainerAppExtensions.PublishAsAzureContainerAppJob" />. A manually triggered job doesn't run until you start it. To start it during deployment, see [Ensure successful migrations deployment](#ensure-successful-migrations-deployment).
- On Docker Compose, set the service's restart policy to `no` with <ApiReference name="Aspire.Hosting.DockerComposeServiceExtensions.PublishAsDockerComposeService" />, as shown in the following example.
- On Kubernetes, customize the generated manifest to use a `Job` workload, or set `restartPolicy: OnFailure`.

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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](https://www.nuget.org/packages/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.

</Pivot>

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.

<LearnMore>
  For more information, see [Deploy with Aspire](/deployment/deploy-with-aspire/), [Persistent volumes on Kubernetes](/deployment/kubernetes/persistent-volumes/), [Run as a local container during development](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/#run-as-a-local-container-during-development), and [Database creation after initial deployment](/integrations/cloud/azure/azure-postgresql/azure-postgresql-host/#database-creation-after-initial-deployment).
</LearnMore>

### 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:

<Pivot id="efcore">

- [Add a custom step to the Aspire deployment pipeline](#run-migrations-in-the-deployment-pipeline) so that `aspire deploy` runs 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](#run-migrations-as-a-cicd-pre-deployment-step) before you call `aspire deploy`.

</Pivot>

<Pivot id="drizzle">

- [Add a custom step to the Aspire deployment pipeline](#run-migrations-in-the-deployment-pipeline) so that `aspire deploy` runs a migration job and waits for it to succeed before it updates the app.
- [Run `drizzle-kit migrate` in your CI/CD pipeline](#run-migrations-as-a-cicd-pre-deployment-step) before you call `aspire deploy`.

</Pivot>

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

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:

1. Runs after the step that creates or updates the migration job.
1. Starts the job and waits for it to finish. If the job fails, the step throws an error, and the pipeline stops.
1. 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](https://www.nuget.org/packages/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.

<Pivot id="efcore">

Publish the migration bundle as a container image and deploy it as a manually triggered job with <ApiReference name="Aspire.Hosting.ContainerAppExtensions.PublishAsAzureContainerAppJob" />. 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`:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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();
}
```

</Pivot>

<Pivot id="drizzle">

Deploy the `db:migrate` script from [Apply schema migrations on startup](#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`:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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.

</Pivot>

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.

<LearnMore>
  For more information, see [Pipelines and app topology](/deployment/pipelines/), [Azure Container Apps jobs](/integrations/cloud/azure/container-app-jobs/), and [Jobs in Azure Container Apps](https://learn.microsoft.com/azure/container-apps/jobs) in the Azure documentation.
</LearnMore>

#### 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.

<Pivot id="efcore">

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:

```typescript title="apphost.mts"
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();
```

```csharp title="AppHost.cs"
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:

```bash title="Terminal"
# 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 deploy
```

Store 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.

<LearnMore>
  For more information, see [Migration bundles](https://learn.microsoft.com/ef/core/managing-schemas/migrations/applying#bundles) in the EF Core documentation and the [`aspire do` command](/reference/cli/commands/aspire-do/).
</LearnMore>

</Pivot>

<Pivot id="drizzle">

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](#apply-schema-migrations-on-startup) reads the connection string from the `CATALOGDB_URI` environment variable:

```bash title="Terminal"
# 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 deploy
```

Store the connection string in your CI/CD system's secret store, and make sure the agent can reach the database through its firewall.

</Pivot>

## See also

- [PostgreSQL integration](/integrations/databases/postgres/postgres-host/)
- [Entity Framework Core integrations overview](/integrations/databases/efcore/overview/)
- [Apply EF Core migrations in Aspire](/integrations/databases/efcore/migrations/)
- [Seed data in a database using Aspire](/integrations/databases/efcore/seed-database/)
- [JavaScript integration](/integrations/frameworks/javascript/)
- [Drizzle ORM documentation](https://orm.drizzle.team/docs/overview)
- [EF Core documentation](https://learn.microsoft.com/ef/core/)