Introduction
In the previous lessons, we combined services, databases, Redis, and RabbitMQ in one Aspire AppHost application model. This lesson moves the application one step closer to a deployment-ready topology by focusing on container-based local execution. The objective is not only to write a Dockerfile. We will build repeatable service images, represent those images as container resources in the Aspire model, manage ports and volumes, and verify that the complete distributed application behaves correctly on a local container runtime.
There are two useful approaches with Aspire. In the first, ASP.NET Core projects run as local processes while infrastructure dependencies such as SQL Server, Redis, and RabbitMQ run in containers. In the second, the application services themselves are built and started as containers from Dockerfiles. This lesson focuses on the second approach and on the validation activities that make local container deployment reliable.
Local container deployment is not a complete copy of production, but it gives us an early and repeatable way to test image builds, networking, environment values, volumes, startup dependencies, and service health.
1. Dockerfiles and container images
A Dockerfile describes the steps required to build a container image. An image can be treated as an immutable package containing application files, a runtime, and the operating-system components required by the application. A container is a running instance of that image.
ASP.NET Core applications commonly use a multi-stage Dockerfile. The first stage uses the .NET SDK image to restore, build, and publish the application. The second stage uses only the ASP.NET Core runtime image and copies the published output into it. This keeps the final image smaller and prevents build tools from being included in the runtime environment.
Example Catalog Dockerfile
# Catalog/Dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["Catalog/Catalog.csproj", "Catalog/"]
RUN dotnet restore "Catalog/Catalog.csproj"
COPY . .
WORKDIR "/src/Catalog"
RUN dotnet publish "Catalog.csproj" \
-c Release \
-o /app/publish \
--no-restore
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
EXPOSE 8080
ENTRYPOINT ["dotnet", "Catalog.dll"]The build stage restores dependencies and produces the publish output. The runtime stage contains only that output and the ASP.NET Core runtime. When working with .NET 10 container images, the SDK and runtime image versions should match the target framework used by the project. Pinning image tags provides more predictable builds across developer machines and CI environments.
Container ports
EXPOSE 8080 documents the port used inside the container. It does not, by itself, publish port 8080 on the host machine. Host-to-container port mapping is provided by Aspire or by Docker runtime arguments. The ASP.NET Core application should also be configured to listen on the intended port:
ENV ASPNETCORE_HTTP_PORTS=8080Application code should not contain hard-coded localhost addresses. Container environments should use the endpoints and service discovery values supplied by the application model.
2. Defining Dockerfile resources in the Aspire AppHost
The AddDockerfile method creates a new container resource from an existing Dockerfile. Relative context paths are interpreted relative to the AppHost project. Assume the solution has this structure:
src/
AppHost/
AppHost.csproj
AppHost.cs
Catalog/
Catalog.csproj
Dockerfile
Order/
Order.csproj
Dockerfile
Inventory/
Inventory.csproj
DockerfileThe services can then be added to the AppHost from their Dockerfile contexts:
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithDataVolume();
var redis = builder.AddRedis("cache")
.WithDataVolume();
var rabbit = builder.AddRabbitMQ("messaging")
.WithDataVolume();
var catalog = builder.AddDockerfile("catalog", "../Catalog")
.WithReference(sql)
.WithReference(redis)
.WaitFor(sql)
.WaitFor(redis);
var order = builder.AddDockerfile("order", "../Order")
.WithReference(sql)
.WithReference(rabbit)
.WaitFor(sql)
.WaitFor(rabbit);
var inventory = builder.AddDockerfile("inventory", "../Inventory")
.WithReference(sql)
.WithReference(rabbit)
.WaitFor(sql)
.WaitFor(rabbit);
builder.Build().Run();SQL Server, Redis, and RabbitMQ are added as infrastructure container resources, while the services are built from their own Dockerfiles. WithReference connects the resource relationships and helps provide the appropriate connection and service-discovery configuration. WaitFor expresses startup dependencies in the application model. It does not eliminate the need for application-level retry and health-check behavior.
The difference between AddDockerfile and WithDockerfile
AddDockerfile creates a new container resource. It is appropriate for a custom ASP.NET Core service or another service that is not already represented by an Aspire component. WithDockerfile customizes an existing container resource. For example, if a Redis resource needs a custom image built from a Dockerfile, WithDockerfile can replace the default image while preserving the strongly typed resource configuration.
3. Managing ports, endpoints, and environment values
The internal container port and the host port are different concepts. A service may listen on port 8080 inside its container while Aspire exposes it through a dynamically selected local endpoint. Service-to-service communication should use resource references and service discovery rather than hard-coded host ports.
For example, the Order service should not call Catalog through a URL such as http://localhost:8081. Instead, it should use the logical service name supplied by the application model. This allows the same topology to work with different local port assignments and with other deployment targets.
Environment values that change between environments should be supplied by the AppHost or the runtime rather than permanently written into the Dockerfile. For example:
var catalog = builder.AddDockerfile("catalog", "../Catalog")
.WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development")
.WithEnvironment("DOTNET_DiagnosticsMonitorAddress", "http://0.0.0.0:9000");Secrets must not be placed in Dockerfiles or committed to source control. Connection strings, passwords, and access tokens should be supplied through parameters, secret stores, or local development secret mechanisms. A secret written into an image layer may remain in the image history, so deleting the file in a later layer is not a sufficient security measure.
4. Volumes and data persistence
A container file system should generally be treated as temporary. Stateful components such as SQL Server, Redis, and RabbitMQ need volumes if their local data must survive container recreation. An Aspire resource can declare a data volume:
var sql = builder.AddSqlServer("sql")
.WithDataVolume("course-sql-data");
var redis = builder.AddRedis("cache")
.WithDataVolume("course-redis-data");A volume is not the same as a backup strategy. Local volumes belong to a developer machine and are not automatically shared across a team. Production systems require separate decisions about managed databases, backups, snapshots, retention, and recovery testing.
Stateless API containers normally do not need persistent volumes. Instead of writing application logs into the container file system, send logs to standard output and let the surrounding logging system collect them.
5. Building images and running locally
Before using Aspire, test that each Dockerfile works with the intended build context:
docker build -f Catalog/Dockerfile -t course/catalog:dev .
docker image ls course/catalog
docker run --rm -p 8081:8080 \
-e ASPNETCORE_ENVIRONMENT=Development \
course/catalog:devIn this example, the build context is the solution root and the Dockerfile is located in the Catalog directory. If the context is wrong, COPY instructions may not find the solution files or referenced projects. After the container starts, call a health endpoint:
curl http://localhost:8081/healthWhen the AppHost starts the application model, Aspire can manage the image-build and resource lifecycle:
aspire runUse the Aspire Dashboard to inspect resource state, endpoints, logs, and health information. If a container fails to start, inspect the image-build output first, then container logs, environment values, port conflicts, and dependency health.
Producing a Docker Compose deployment output
The application model can also produce container-oriented deployment artifacts. A Docker Compose deployment environment can be added to the AppHost:
var builder = DistributedApplication.CreateBuilder(args);
builder.AddDockerComposeEnvironment("docker");
var sql = builder.AddSqlServer("sql").WithDataVolume();
var redis = builder.AddRedis("cache").WithDataVolume();
var catalog = builder.AddDockerfile("catalog", "../Catalog")
.WithReference(sql)
.WithReference(redis);
builder.Build().Run();When Compose artifacts are generated from this model, services, networks, volumes, and required environment values are represented in the target format. The output can be used for local validation or handed to another tool. Prefer changing the AppHost model over manually editing generated Compose files so that the application topology remains the source of truth.
6. A step-by-step validation checklist
- Check the container runtime: Docker Desktop or another supported container runtime must be running.
- Verify the Dockerfile context: Every
COPYpath must be inside the selected build context. - Build each image: Review warnings and errors instead of assuming a successful command means a correct image.
- Start the containers: Check that host ports are not already used by another process.
- Call health endpoints: Confirm that the service and its dependencies are ready, not merely that the process exists.
- Test service communication: Verify that resource names and service discovery are used instead of fixed localhost URLs.
- Test persistence: Recreate a SQL Server or Redis container and confirm that the declared volume preserves the intended data.
- Inspect observability: Confirm that logs, traces, and metrics are associated with the expected resource.
Common mistakes
Using the wrong build context
If the Catalog directory is selected as the context while the Dockerfile expects solution-level files, shared projects and solution references may not be available. Choose the context and Dockerfile path deliberately.
Confusing container and host ports
EXPOSE 8080 does not guarantee that the host machine is listening on port 8080. Inspect the endpoint generated by Aspire or the explicit Docker port mapping.
Using localhost for another service
Inside a container, localhost refers to that same container. It does not refer to the host or another container. Use service discovery and resource references for inter-service calls.
Embedding secrets in the image
Passwords supplied through Dockerfile ENV or ARG values can become visible in image metadata or layers. Supply secrets at runtime and consider the complete image history.
Calling a dependency too early
A started process does not necessarily mean that SQL Server accepts connections or that RabbitMQ is ready. Combine health checks, retries, and explicit dependency relationships.
Practice exercise
In this exercise, start the Catalog and Order services as containers.
- Create a multi-stage .NET 10 Dockerfile for each service.
- Define
catalogandorderwithAddDockerfilein the AppHost. - Add a Redis reference to Catalog and a RabbitMQ reference to Order.
- Set the Development environment for both services.
- Declare a data volume for SQL Server and connect the services with
WaitFor. - Run the application with
aspire run. - Inspect image build output, resource health, logs, and endpoints in the Dashboard.
- Verify that an Order-to-Catalog HTTP request does not use a fixed localhost URL.
- Restart the SQL Server resource and confirm whether the declared volume preserves the expected data.
Conclusion
In this lesson, we created small and repeatable ASP.NET Core runtime images with multi-stage Dockerfiles. We represented those images as Dockerfile-based container resources in an Aspire AppHost and modeled service references, startup dependencies, ports, environment values, and data volumes. We also validated image builds, health endpoints, service-to-service communication, and data persistence in a local container environment.
This approach provides a practical foundation for the publishing and deployment topics that follow. Running the same resource graph as containers before production helps expose missing files, incorrect ports, invalid connection settings, and startup-order problems early. The main value of Aspire is not simply starting containers; it is expressing those containers and their relationships as one application model that can be inspected, validated, and reused.