📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How would you use Docker Compose to run a .NET 10 API locally with SQL Server and Redis? Explain services, networks, volumes, health checks and depends_on, and when you would use .NET Aspire or Testcontainers instead.

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.

Junior Theory Beginner containers devops docker-compose local-development redis sql-server

🎯 Key points

  • compose.yaml declares services, networks and volumes; run with `docker compose up` (Compose v2 CLI plugin)
  • Services reach each other by service name on the default network (sqlserver:1433)
  • Named volumes keep database data between restarts
  • healthcheck + depends_on condition: service_healthy for start order; app still retries
  • Config via environment variables with __ for nesting (ConnectionStrings__Default)
  • Local-only passwords from a git-ignored .env file (variable substitution / env_file); never production secrets
  • Pin image tags to match production versions instead of floating tags
  • .NET Aspire AppHost or Testcontainers as alternatives for dev and tests

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Compose is how I give a new developer the whole stack with one command. In compose.yaml I declare three services. The api service builds from the project's Dockerfile and maps host port 5000 to container port 8080. The sqlserver service uses mcr.microsoft.com/mssql/server with ACCEPT_EULA=Y and an SA password from a local .env file, 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 is Server=sqlserver,1433 and the Redis endpoint is redis:6379. Inside the network I use the container port, not the host-mapped one.

Two details make it reliable. First, depends_on on its own only orders container start, not readiness, and SQL Server needs several seconds before it accepts logins. So I give SQL Server a healthcheck that runs sqlcmd with SELECT 1, and the API uses depends_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, so docker compose down keeps the data and down -v resets it. Configuration flows in as environment variables, using double underscores for nesting, like ConnectionStrings__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."


The key Compose concepts

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"]

Compose versus the alternatives

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can set up a reproducible local stack and understands container networking, readiness and configuration.

Green flags

  • Uses service names and container ports between services
  • Health check with service_healthy, plus retries in the app
  • Named volumes, pinned image tags, and a git-ignored .env whose values Compose substitutes into ${...} (or loads with env_file)
  • Keeps local-only secrets separate from real environments, where managed identity and Key Vault take over
  • Knows Aspire and Testcontainers as alternatives

Red flags

  • localhost in the connection string
  • Passwords committed to the repo
  • Thinks Compose is a production orchestrator

📚 Learn in depth

1. What Compose creates

 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.

2. Start order versus readiness

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.

3. Volumes versus bind mounts

  • Named volume (sqldata:/var/opt/mssql): managed by Docker, fast, survives down, removed with down -v.
  • Bind mount (./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.

4. Configuration

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.

5. SQL Server and Redis images

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

6. Compose in CI

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.

Try it yourself

  1. Write the compose.yaml below, run docker compose up -d --wait, then docker compose ps to see health.
  2. Remove the health check condition and watch the API fail its first connection attempt.
  3. Run docker compose exec api ... and notice a chiseled image has no shell; use docker compose logs api instead.
  4. Run docker compose down then up and confirm data survived; then down -v.
  5. Recreate the same stack as a .NET Aspire AppHost and compare.

💻 Code

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

⚠ Common mistakes

  • Mistake: Relying on plain 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.
  • Mistake: Using 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.
  • Mistake: Using the host-mapped port between containers. Why it is wrong: Containers talk on the internal network on the container port. Instead: sqlserver:1433, not 14333.
  • Mistake: Committing the SA password in compose.yaml. Why it is wrong: Habits leak into real environments and secret scanners flag it. Instead: ${SA_PASSWORD} from a git-ignored .env.
  • Mistake: Floating image tags such as 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.
  • Mistake: Copying the health check command from an old blog post. Why it is wrong: The 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.
  • Mistake: Removing 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.
  • Mistake: No volume for the database. Why it is wrong: Data disappears whenever the container is recreated. Instead: A named volume on /var/opt/mssql.
  • Mistake: Using Compose as the production deployment. Why it is wrong: No self-healing across hosts, rolling updates, secrets management or scaling. Instead: Container Apps, AKS or App Service, with Compose only for local and CI.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate maps ports between host and container Why: Checks they can debug a container that doesn't answer on its port
    How to answer

    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.

  2. When: Candidate configures the API with environment variables Why: Checks they understand configuration provider precedence and naming
    How to answer

    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:

    • Naming: : in a Linux App Service or Kubernetes variable instead of __; App Service connection strings arriving as SQLAZURECONNSTR_*.
    • Precedence: a JSON file or App Configuration added after the defaults overrides environment variables.
    • Wrong environment: ASPNETCORE_ENVIRONMENT unset, so appsettings.Production.json loads.
    • Timing: environment variables are read once; 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.

  3. When: Candidate mentions Testcontainers Why: Checks they can test data access against a real engine, not an in-memory fake
    How to answer

    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.

↩ Usually asked after

More in Containers

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me