Introduction
Docker Compose is a popular choice for running multiple application services during local development. Developers can define an API, database, Redis cache, message broker, and other dependencies in a single YAML file. With one command, Docker Compose starts the required containers and connects them through a shared network.
As an application grows, however, managing its development environment can become more complicated. Some services may run inside containers, while others run directly on the developer's machine. Developers may also need to manage connection strings, service dependencies, health checks, environment variables, and application logs separately.
.NET Aspire provides another way to manage this environment. Instead of defining the complete application setup in a Docker Compose YAML file, developers can describe resources in a strongly typed AppHost project using C#.
Aspire also supports more than containers. It can manage .NET projects, Node.js applications, executable processes, databases, caches, and other resources together.
This does not mean Docker Compose is no longer useful. Both tools solve related problems, and the right choice depends on the application and development workflow.
In this article, we will take a simple Docker Compose application and gradually move its services into a .NET Aspire AppHost. We will cover service definitions, database configuration, environment variables, persistent storage, service dependencies, and common migration challenges.
Understanding the Difference Between Docker Compose and .NET Aspire
Before migrating an existing setup, it is important to understand how both tools organize application resources.
Docker Compose uses a YAML file to describe containers, networks, volumes, ports, and environment variables. Developers can start and stop the complete environment using Docker Compose commands.
.NET Aspire uses an AppHost project to describe application resources in C#. Instead of defining everything in YAML, developers register resources using methods such as AddProject, AddContainer, AddPostgres, and AddRedis.
The main difference is that Docker Compose focuses on managing container-based applications, while Aspire provides a broader development model that can manage containers and local application processes together.
Feature | Docker Compose | .NET Aspire |
|---|
Configuration | YAML file | C# or TypeScript AppHost |
Application resources | Primarily containers | Containers, projects, executables, and other resources |
Service dependencies | depends_on | WaitFor |
Service configuration | Environment variables | Resource references and environment variables |
Service discovery | Container DNS and networks | Aspire service discovery |
Persistent storage | Volumes and bind mounts | Volumes and bind mounts |
Monitoring | Container logs and health checks | Dashboard, logs, health, and telemetry |
Local .NET debugging | Usually requires separate tooling | Direct project integration |
One important point is that Aspire does not simply convert every Docker Compose feature into an identical AppHost feature. Some concepts, such as custom network isolation, require a different approach.
Step 1. Understand the Existing Docker Compose Setup
Let's start with a simple application containing three services:
A simplified Docker Compose configuration might look like this:
services:
api:
build:
context: ./Api
ports:
- "5000:8080"
environment:
- ConnectionStrings__DefaultConnection=Host=postgres;Database=appdb;Username=appuser;Password=secret
- Redis__ConnectionString=redis:6379
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
postgres:
image: postgres:17
environment:
POSTGRES_DB: appdb
POSTGRES_USER: appuser
POSTGRES_PASSWORD: secret
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U appuser -d appdb"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7
ports:
- "6379:6379"
volumes:
postgres_data:
This configuration starts the API, PostgreSQL, and Redis containers.
The API uses the service names postgres and redis to connect to the database and cache from inside the Compose network.
The database uses a named volume to preserve its data even when the container is stopped or recreated.
The health check verifies that PostgreSQL is ready to accept connections before the API starts.
Before migrating this configuration, identify what each service needs. Pay attention to ports, environment variables, image versions, volumes, health checks, and dependencies. These details are important because missing configuration can cause problems after moving to Aspire.
Step 2. Create a .NET Aspire AppHost
If you already have an Aspire solution, you can use its existing AppHost project.
Otherwise, create a new Aspire starter solution:
dotnet new aspire-starter -n AspireMigration
Navigate to the solution directory:
cd AspireMigration
The starter template creates the AppHost and supporting projects. You can add your existing API project to the solution rather than rewriting it.
For example, the solution can have the following structure:
AspireMigration/
│
├── AspireMigration.AppHost/
│ └── Program.cs
│
├── AspireMigration.ServiceDefaults/
│ └── Extensions.cs
│
└── Api/
├── Api.csproj
└── Program.cs
The AppHost project will describe how the API, PostgreSQL, and Redis resources work together.
The API project will continue to contain its existing business logic and HTTP endpoints.
This is an important benefit of the migration. You do not need to rewrite your application just because you are changing the local development orchestration tool.
Step 3. Add PostgreSQL and Redis to the AppHost
The first migration step is to register the infrastructure services.
Add the required hosting integrations to the AppHost project:
dotnet add AspireMigration.AppHost package Aspire.Hosting.PostgreSQL
dotnet add AspireMigration.AppHost package Aspire.Hosting.Redis
Now open the AppHost Program.cs file and register PostgreSQL and Redis:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres")
.WithImageTag("17")
.WithDataVolume();
var database = postgres.AddDatabase("appdb");
var redis = builder.AddRedis("redis")
.WithImageTag("7");
builder.Build().Run();
Let's understand the configuration.
The AddPostgres method registers a PostgreSQL resource with the name postgres.
WithImageTag specifies the PostgreSQL image version. Pinning an image version helps keep the local development environment consistent instead of allowing an unexpected image update.
WithDataVolume adds persistent storage for the PostgreSQL data. This is important because database data should not disappear whenever the development environment is restarted.
The AddDatabase method creates a logical database named appdb within the PostgreSQL server.
Similarly, AddRedis registers a Redis resource using the Redis 7 image.
At this stage, Aspire knows about both infrastructure resources, but the API has not yet been connected to them.
Step 4. Connect the API to PostgreSQL and Redis
In Docker Compose, the API receives connection information through environment variables.
In Aspire, we can use WithReference to provide connection information and service discovery configuration to an application.
First, add the API project reference to the AppHost project if it is not already included:
dotnet add AspireMigration.AppHost reference Api/Api.csproj
Now update the AppHost Program.cs file:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres")
.WithImageTag("17")
.WithDataVolume();
var database = postgres.AddDatabase("appdb");
var redis = builder.AddRedis("redis")
.WithImageTag("7");
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database)
.WithReference(redis)
.WaitFor(database)
.WaitFor(redis);
builder.Build().Run();
The WithReference method connects the API resource to the required infrastructure resources.
For the database reference, Aspire supplies a connection string through application configuration. Its default configuration key is based on the database resource name.
For example, the database resource named appdb is available through the ConnectionStrings configuration section under appdb.
The API can access it using the standard .NET configuration system or an Aspire client integration.
The WaitFor method defines startup dependencies. In this example, the API waits for PostgreSQL and Redis to become ready before starting its dependent operations.
WithReference and WaitFor have different responsibilities. WithReference provides resource information and connection configuration, while WaitFor controls startup ordering based on dependency readiness.
This distinction is important when migrating Docker Compose configurations because depends_on can express startup dependencies, but it does not automatically translate into a single Aspire method.
Step 5. Update the API Configuration
Now update the API project so that it uses the connection information provided by Aspire.
Add the required packages:
dotnet add Api package Aspire.Npgsql
dotnet add Api package Aspire.StackExchange.Redis
Open the API Program.cs file:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDataSource("appdb");
builder.AddRedisClient("redis");
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapGet("/", () => "API is running.");
app.Run();
The AddServiceDefaults method applies common development configuration such as health checks and OpenTelemetry support when the corresponding defaults are configured.
The AddNpgsqlDataSource method registers a PostgreSQL data source using the connection string supplied through Aspire.
The AddRedisClient method registers a Redis client using the Redis connection information supplied by the AppHost.
The API can now access PostgreSQL and Redis without manually maintaining container hostnames and dynamically assigned ports.
If your existing API already uses a different configuration key, you do not have to rename every configuration setting. You can provide a named reference or map the Aspire connection information to the configuration key expected by your application.
For example, if the API expects DefaultConnection instead of appdb, the AppHost can use:
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database, "DefaultConnection")
.WithReference(redis)
.WaitFor(database)
.WaitFor(redis);
The API can then continue reading its existing DefaultConnection setting.
Step 6. Migrate Environment Variables and Secrets
Environment variables are another important part of a Docker Compose migration.
A Compose file may contain configuration such as:
environment:
- LOG_LEVEL=Information
- FEATURE_ENABLED=true
- API_KEY=${API_KEY}
In Aspire, ordinary environment variables can be added using WithEnvironment.
For example:
var apiKey = builder.AddParameter(
"apiKey",
secret: true);
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database)
.WithReference(redis)
.WithEnvironment("LOG_LEVEL", "Information")
.WithEnvironment("FEATURE_ENABLED", "true")
.WithEnvironment("API_KEY", apiKey);
The AddParameter method creates a configurable parameter. Setting secret to true marks the parameter as sensitive.
The value can be supplied through the AppHost configuration rather than being written directly into the source code.
This is especially useful when developers need different API keys or service credentials in different environments.
Avoid placing real passwords, tokens, or API keys directly in AppHost.cs or committing them to source control.
Also remember that connection string formats may differ. Aspire integrations usually provide .NET-style connection strings, while an existing application or third-party container may expect a URL such as a PostgreSQL connection URL.
If a service expects a different format, map the value explicitly rather than assuming WithReference will automatically convert it.
Step 7. Migrate Dockerfile-Based Services
Not every service in a Docker Compose setup needs to be converted into a .NET project.
For example, you may have a service that is built from an existing Dockerfile:
services:
reporting:
build:
context: ./Reporting
dockerfile: Dockerfile
In Aspire, use AddDockerfile to register a container resource built from that Dockerfile:
var reporting = builder.AddDockerfile(
"reporting",
"../Reporting");
If the Dockerfile has a custom name, you can configure it using the appropriate Dockerfile resource options.
For services that already have a published container image, use AddContainer instead:
var proxy = builder.AddContainer(
"proxy",
"nginx",
"latest");
These methods are useful when the application contains services that cannot be run directly as .NET project references.
A practical migration approach is to use AddProject for .NET applications that benefit from direct local execution and debugging, AddDockerfile for services that must be built from Dockerfiles, and AddContainer for services that use existing images.
This allows you to migrate gradually without changing how every application is packaged.
Step 8. Migrate Volumes and Persistent Storage
Docker Compose supports named volumes and bind mounts.
Named volumes are commonly used for database storage, while bind mounts allow containers to access files from the developer's machine.
For example:
volumes:
- postgres_data:/var/lib/postgresql/data
- ./config:/app/config:ro
The equivalent Aspire configuration uses volume and bind-mount methods.
For a PostgreSQL resource, WithDataVolume is a convenient way to add persistent database storage.
For a custom container, you can create a named volume:
var sharedData = builder.AddVolume("shared-data");
var reporting = builder.AddContainer(
"reporting",
"my-reporting-service",
"latest")
.WithVolume(sharedData, "/app/data");
For a directory on the developer's machine, use a bind mount:
var configService = builder.AddContainer(
"config-service",
"my-config-service",
"latest")
.WithBindMount(
"../config",
"/app/config",
isReadOnly: true);
The isReadOnly setting prevents the container from modifying the mounted configuration files.
Before migrating volumes, check the original container paths and access permissions. A volume mounted at the wrong location can make an application appear to have lost its data even when the original data still exists.
Step 9. Understand Service Discovery and Networking
Docker Compose automatically creates a network for its services. Containers can communicate using service names such as postgres, redis, and api.
Aspire handles service discovery differently.
When an application resource references another resource, Aspire can provide the required connection information through configuration and service discovery support.
For example, a .NET application can use Aspire service discovery with an HTTP client:
builder.Services.AddHttpClient("Inventory")
.AddServiceDiscovery();
The AppHost can provide a reference to the inventory API:
var inventoryApi = builder.AddProject<
Projects.InventoryApi>("inventory-api");
var orderApi = builder.AddProject<
Projects.OrderApi>("order-api")
.WithReference(inventoryApi);
The Order API can use the service name through its configured HTTP client instead of depending on a fixed local port.
However, do not assume that every networking feature from Docker Compose has a direct Aspire equivalent.
For example, Docker Compose supports custom network segmentation that can isolate groups of containers. Aspire does not provide an identical custom-network isolation model for its local application resources.
If your existing application depends on network-level security boundaries, review that design separately. Application authorization, firewall rules, and deployment infrastructure may be required to preserve those security boundaries.
Step 10. Run and Validate the Migrated Application
Once the resources are registered, start the application through the AppHost:
dotnet run --project AspireMigration.AppHost
Aspire starts the PostgreSQL and Redis resources and then starts the API according to the configured dependencies.
Open the Aspire dashboard address displayed in the terminal.
Verify that:
PostgreSQL has started successfully.
Redis is available.
The API has started.
The API can connect to PostgreSQL.
The API can connect to Redis.
The application logs do not contain connection errors.
Test the API endpoints using a browser, HTTP client, or your existing integration tests.
Also verify that PostgreSQL data remains available after stopping and restarting the development environment. This confirms that persistent storage is configured correctly.
Do not remove your original Compose configuration immediately. Keep it available until the Aspire environment has been tested and the development team has confirmed that all required services behave as expected.
Common Migration Mistakes
Mistake | Why It Happens | Solution |
|---|
API cannot connect to the database | Connection string configuration has changed | Verify the resource reference and expected configuration key |
API starts before the database is ready | WithReference is used without a startup dependency | Add WaitFor where startup readiness is required |
Database data disappears | Persistent storage was not configured | Add a data volume or named volume |
Container cannot access a local file | Bind mount path or permissions are incorrect | Verify the host path and container destination |
Redis connection fails | The application expects a different connection format | Check the Redis client configuration |
Existing service name no longer works | Docker Compose DNS assumptions were retained | Configure Aspire service discovery or explicit endpoints |
Secrets appear in source control | Credentials were hardcoded during migration | Use secret parameters and secure configuration |
Best Practices
Migrate One Service at a Time
Avoid moving every service at once. Start with infrastructure services such as PostgreSQL and Redis, then migrate the API and remaining application components.
This makes it easier to identify configuration problems and compare the new environment with the original Compose setup.
Keep Image Versions Consistent
Use explicit image tags instead of relying on latest. This helps prevent unexpected changes when developers start the application on different machines.
Preserve Existing Application Configuration Where Possible
A migration should not require unnecessary changes to application business logic.
Use named references and environment variable mappings when existing applications depend on established configuration keys.
Review Storage Before Restarting Services
Persistent data is often more important than the container itself. Confirm that volumes and bind mounts are correctly configured before removing or replacing the original Compose environment.
Keep Production Deployment Separate From Local Development
Moving local orchestration to Aspire does not automatically mean that the production environment must change.
You can continue using an existing deployment platform while adopting Aspire for local development. Aspire also supports deployment workflows, including Docker Compose publishing, but those are separate decisions from running the AppHost locally.
Advantages and Disadvantages
Advantages
Manages .NET projects and containers through one AppHost.
Reduces manual connection string and port configuration.
Provides a shared dashboard for resource status and application logs.
Supports direct debugging of .NET projects.
Makes service dependencies easier to understand.
Allows services to be migrated gradually.
Disadvantages
Requires developers to learn the Aspire resource model.
Existing Compose configurations may need manual changes.
Some networking and container-specific features do not have direct equivalents.
Incorrect volume or connection string mappings can cause migration issues.
Teams that rely heavily on YAML-based workflows may prefer to keep Docker Compose.
Summary
Docker Compose and .NET Aspire both help developers manage multi-service applications, but they approach the problem differently.
Docker Compose uses YAML to define containers, networks, and volumes. Aspire uses an AppHost project to describe a broader application environment that can include containers, .NET projects, and other resources.
In this article, we moved a sample API, PostgreSQL database, and Redis cache from Docker Compose into an Aspire AppHost. We also covered service references, startup dependencies, environment variables, secrets, Dockerfile-based services, volumes, and service discovery.
The best approach is to migrate incrementally. Review the existing Compose configuration, register the infrastructure resources, connect the application projects, and validate the complete environment before removing the old setup.
This makes the transition easier to manage while allowing developers to take advantage of Aspire's integrated local development and monitoring experience.
Join the conversation! Your thoughts help the community grow.