Docker Compose for local .NET development: compose.yaml services for the API, SQL Server and Redis, service-name DNS, named volumes, health checks with depends_on conditions, environment configuration, and the Aspire and Testcontainers alternatives.
Docker Compose describes a multi-container app in a compose.yaml: each service (the API, mcr.microsoft.com/mssql/server, redis) gets an image or build context, ports, environment variables and volumes. docker compose up starts them on a shared network where they find each other by service name, so the API connects to Server=sqlserver,1433.
I add a health check to SQL Server and depends_on: condition: service_healthy to the API, because SQL Server takes several seconds to accept logins. A named volume keeps the data between runs.
It is for local development and CI, not production. In a .NET-only solution, .NET Aspire does the same orchestration in C# with dashboards, and Testcontainers is better for integration tests.
"Compose is how I give a new developer the whole stack with one command. In
compose.yamlI declare three services. The api service builds from the project's Dockerfile and maps host port 5000 to container port 8080. The sqlserver service usesmcr.microsoft.com/mssql/serverwithACCEPT_EULA=Yand an SA password from a local.envfile, and the redis service uses the official Redis image. Compose creates a default network, and Docker's embedded DNS resolves each service name, so the API's connection string isServer=sqlserver,1433and the Redis endpoint isredis:6379. Inside the network I use the container port, not the host-mapped one.Two details make it reliable. First,
depends_onon its own only orders container start, not readiness, and SQL Server needs several seconds before it accepts logins. So I give SQL Server ahealthcheckthat runssqlcmdwithSELECT 1, and the API usesdepends_on: sqlserver: condition: service_healthy. I still keep EF Core's retry-on-failure, because the app should cope with a database that blips. Second, I put the database files on a named volume, sodocker compose downkeeps the data anddown -vresets it. Configuration flows in as environment variables, using double underscores for nesting, likeConnectionStrings__Default.The mistake I see is treating the Compose file as the production deployment, with the SA password committed in it. Compose is a local and CI tool. If the solution is all .NET, I now often use a .NET Aspire AppHost instead, which describes the same resources in C# and gives me a telemetry dashboard, and for integration tests I use Testcontainers so each test run gets a fresh database."
| Concept | What it does | Example |
|---|---|---|
services |
Containers to run | api, sqlserver, redis |
build / image |
Build from a Dockerfile or pull an image | build: ./src/Orders.Api |
ports |
Host:container mapping, for access from your machine | "5000:8080" |
environment / env_file |
Configuration | ConnectionStrings__Default=... |
volumes |
Persistent or bind-mounted storage | sqldata:/var/opt/mssql |
healthcheck |
Command that reports readiness | sqlcmd ... -Q "SELECT 1" |
depends_on + condition |
Start order, optionally wait for healthy | service_healthy |
profiles |
Optional services | profiles: ["observability"] |
| Tool | Best for | Not for |
|---|---|---|
| Docker Compose | Polyglot stacks, any team, CI service setup | Production |
| .NET Aspire AppHost | .NET-centric solutions, dashboard, service discovery wiring | Teams not on .NET |
| Testcontainers | Integration tests with a fresh real database per run | Running the app interactively |
On a team of eight, onboarding went from a half-day wiki of installing SQL Server Developer Edition and Redis to git clone and docker compose up, about 4 minutes on first run. Database version drift between laptops disappeared because everyone ran the same pinned SQL Server image.
Checks that the candidate can set up a reproducible local stack and understands container networking, readiness and configuration.
Green flags
service_healthy, plus retries in the app.env whose values Compose substitutes into ${...} (or loads with env_file)Red flags
localhost in the connection string docker compose up
│
▼
network: orders_default (bridge, embedded DNS at 127.0.0.11)
┌──────────────┐ sqlserver:1433 ┌────────────────┐
│ api :8080 │ ─────────────────▶ │ sqlserver:1433 │── volume sqldata
│ (host :5000) │ ───┐ └────────────────┘
└──────────────┘ │ redis:6379 ┌────────────────┐
└─────────────▶ │ redis:6379 │
└────────────────┘
Compose prefixes resources with the project name (the folder name by default), so two projects don't collide. Every service joins the default network and gets a DNS name equal to its service name.
depends_on with no condition waits only until the dependency container is created and started. condition: service_healthy waits until its health check passes. condition: service_completed_successfully waits for a one-off job, which is handy for a migration container (for example an EF Core migration bundle) that runs before the API.
sqldata:/var/opt/mssql): managed by Docker, fast, survives down, removed with down -v../seed:/seed): maps a host folder; good for seed scripts or hot reload, slower on macOS and Windows, and a source of permission problems because the SQL Server image runs as a non-root mssql user.ASP.NET Core's environment variable provider maps __ to :, so ConnectionStrings__Default becomes ConnectionStrings:Default. Compose substitutes ${SA_PASSWORD} from a .env file next to compose.yaml; that file is in .gitignore. compose.override.yaml is merged automatically, which is a neat place for developer-only settings.
mcr.microsoft.com/mssql/server:2022-latest (a 2025 image is also available) runs SQL Server on Linux. It needs ACCEPT_EULA=Y, a strong MSSQL_SA_PASSWORD, and at least 2 GB of memory. On Apple Silicon it runs under emulation; Azure SQL Edge is retired, so check your team's approach.redis:7 runs Redis; for production on Azure you'd use Azure Managed Redis, not a container.GitHub Actions services: or docker compose up -d --wait in a pipeline step gives integration tests a real SQL Server. --wait blocks until health checks pass.
compose.yaml below, run docker compose up -d --wait, then docker compose ps to see health.docker compose exec api ... and notice a chiseled image has no shell; use docker compose logs api instead.docker compose down then up and confirm data survived; then down -v.A compose.yaml for local development:
services:
api:
build:
context: .
dockerfile: src/Orders.Api/Dockerfile
ports:
- "5000:8080" # host:container
environment:
ASPNETCORE_ENVIRONMENT: Development
# service name 'sqlserver' resolves on the Compose network; use the container port
ConnectionStrings__Default: "Server=sqlserver,1433;Database=Orders;User Id=sa;Password=${SA_PASSWORD};TrustServerCertificate=True"
ConnectionStrings__Redis: "redis:6379"
depends_on:
sqlserver:
condition: service_healthy # wait until SQL Server accepts logins
redis:
condition: service_started
sqlserver:
image: mcr.microsoft.com/mssql/server:2022-latest
environment:
ACCEPT_EULA: "Y"
MSSQL_SA_PASSWORD: "${SA_PASSWORD}" # from .env, which is git-ignored
ports:
- "14333:1433" # so you can connect from SSMS / Azure Data Studio on the host
volumes:
- sqldata:/var/opt/mssql
healthcheck:
test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P \"$${MSSQL_SA_PASSWORD}\" -C -Q 'SELECT 1' || exit 1"]
interval: 10s
timeout: 5s
retries: 10
start_period: 20s
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
sqldata:
The API still retries, because health checks don't guarantee the database never blips:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<OrdersDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("Default"),
sql => sql.EnableRetryOnFailure(maxRetryCount: 5)));
builder.Services.AddStackExchangeRedisCache(options =>
options.Configuration = builder.Configuration.GetConnectionString("Redis"));
var app = builder.Build();
app.MapGet("/healthz", () => Results.Ok());
app.Run();
docker compose up -d --wait # build, start, wait for health checks
docker compose logs -f api
docker compose down # keep data; add -v to wipe the volume
depends_on for readiness. Why it is wrong: It only waits for the container to start; SQL Server needs seconds more, so the API's first connection fails. Instead: Add a health check and condition: service_healthy, and keep retries in the app.localhost in the API's connection string. Why it is wrong: Inside a container localhost is the container itself. Instead: Use the service name, sqlserver,1433.sqlserver:1433, not 14333.compose.yaml. Why it is wrong: Habits leak into real environments and secret scanners flag it. Instead: ${SA_PASSWORD} from a git-ignored .env.latest or 2022-latest in a shared repo. Why it is wrong: Everyone silently gets a new cumulative update on their next pull, so laptops drift from each other and from production. Instead: Pin a specific tag (for example a 2022-CU<n>-ubuntu-22.04 tag) and bump it deliberately.sqlcmd path and flags change between images (recent images ship mssql-tools18 and need -C to trust the self-signed certificate). Instead: Check the command against the exact image tag you pin.TrustServerCertificate=True locally without another fix. Why it is wrong: Microsoft.Data.SqlClient 4+ encrypts by default, and the container's SQL Server uses a self-signed certificate, so the connection fails validation. Instead: Keep it for the local container only, and never use it against Azure SQL, which has a trusted certificate./var/opt/mssql.Compose is an onboarding and parity tool: its job is to make the local stack boring and identical for everyone. I pin image versions to match production (same SQL Server major version and compatibility level as Azure SQL), keep production-only concerns out, and make sure the app itself is resilient so it doesn't depend on Compose start order.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Docker Compose | Mixed-language teams, simple stacks, CI | YAML to maintain; Docker Desktop licence for larger companies | Production |
| .NET Aspire | .NET solutions wanting service discovery and a dashboard | Another project and concepts | Polyglot repos without .NET hosts |
| Testcontainers | Integration tests | Slower test start | Interactive development |
Note that Docker Desktop needs a paid subscription for larger organisations; Podman or Rancher Desktop are common alternatives.
A port is a 16-bit number (0 to 65535) that lets one IP address host many services. A socket is the OS object for one endpoint: a listening socket bound to IP:port, and a connected socket for each accepted connection, identified by the 4-tuple (client IP, client port, server IP, server port).
The Docker problem is almost always binding: the app listens on localhost (127.0.0.1) inside the container, which is unreachable from outside its network namespace, or it listens on a different port from the one you mapped. The official .NET 10 images set ASPNETCORE_HTTP_PORTS=8080, which binds all interfaces on 8080 (the default since .NET 8), so map it with -p 5000:8080 and do not override it with a localhost URL.
Start by proving what the process actually sees, not what the portal says. Use a masked GetDebugView(), which lists every key with the provider that won, or log the provider list at start-up, and run printenv in the container.
The usual causes are:
: in a Linux App Service or Kubernetes variable instead of __; App Service connection strings arriving as SQLAZURECONNSTR_*.ASPNETCORE_ENVIRONMENT unset, so appsettings.Production.json loads.IOptions<T> never reloads; mounted ConfigMaps update by symlink swap, which file watchers miss.The trade-off: configuration layering is flexible, but you must be able to see the final merged result in each environment.
Add the Testcontainers.MsSql package. In an xUnit collection fixture that implements IAsyncLifetime, build an MsSqlContainer with a pinned image, await StartAsync() in InitializeAsync, and await DisposeAsync() in teardown (Testcontainers' Ryuk reaper also removes orphaned containers if a CI job dies). Pass GetConnectionString() to a WebApplicationFactory by overriding configuration, apply EF Core migrations once, and reset data between tests with Respawn. If the container fails to start (for example the CI agent has no Docker), fail fast with a clear message rather than skipping. Each run gets a clean, real SQL Server, catching translation and constraint bugs that the in-memory provider hides.
Last updated 23 Nov 2026.