LESSON 12 OF 14

Health Checks, Startup Ordering, and Migration Automation with Compose

In this lesson, you will verify service readiness with Docker Compose health checks, examine depends_on conditions, and automate Entity Framework Core migrations through a dedicated migration service.

35 dk 64

Introduction

In the previous lesson, we used Docker Compose to run the ASP.NET Core API and SQL Server as one application stack. However, the order in which containers are created is not the same as the order in which services become ready. A SQL Server container may be marked as running while the database engine is still initializing and cannot accept connections. If the API tries to connect during that interval, startup errors may occur.

This lesson addresses the problem in three parts. First, we will define a real health check for SQL Server. Next, we will make the API wait until the database is healthy. Finally, we will run Entity Framework Core migrations through a one-time migration service instead of coupling schema changes directly to the API process. This gives us a predictable startup sequence and useful logs for diagnosing failures.

1. Running is not the same as being ready

Docker generally reports a container as running while its main process is alive. That does not prove that the application is ready to receive requests or accept database connections. During its initial startup, SQL Server may create system databases, initialize data files, and configure the sa account. Connection attempts made before those operations finish can fail.

The short form of depends_on only expresses a creation and startup order:

services:  api:    depends_on:      - db  db:    image: postgres:latest

This prevents the API service from being created before the database service, but it does not prove that the database is ready. For readiness checks, use healthcheck together with the long form of depends_on and condition: service_healthy.

2. Defining a SQL Server health check

A health check is a command that Docker executes inside the container at regular intervals. A successful command marks the service as healthy; repeated failures mark it as unhealthy. For SQL Server, the most useful check is a real query against the local SQL Server instance.

The following example keeps the service names used in the earlier lessons. The password is supplied through a .env file rather than being hard-coded in the Compose file:

services:  db:    image: mcr.microsoft.com/mssql/server:2022-latest    environment:      ACCEPT_EULA: "Y"      MSSQL_PID: "Developer"      MSSQL_SA_PASSWORD: "${SA_PASSWORD}"    ports:      - "1433:1433"    volumes:      - sqlserver-data:/var/opt/mssql    healthcheck:      test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -C -Q \"SELECT 1\" -b -o /dev/null"]      interval: 10s      timeout: 5s      retries: 12      start_period: 30s volumes:  sqlserver-data:

start_period gives SQL Server time to initialize. interval specifies the delay between checks, timeout limits the duration of one check, and retries controls how many failures are allowed. The doubled dollar sign is important: $$MSSQL_SA_PASSWORD tells Compose to pass the variable reference into the container instead of expanding it on the host.

The location of sqlcmd can vary between SQL Server image versions. Verify the path in the image with:

docker compose run --rm db sh -c 'command -v sqlcmd || find /opt -name sqlcmd 2>/dev/null'

If the tool is installed in a different location, update the health check command. The goal is to verify that SQL Server can execute a query, not merely that port 1433 is open.

3. Creating an API health endpoint

It is useful to distinguish between liveness and readiness. Liveness indicates that the process is running. Readiness indicates that the application and its required dependencies are ready to serve requests. ASP.NET Core health checks can expose a controlled endpoint for this purpose.

Add the following registration to Program.cs:

using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddDbContext<ApplicationDbContext>(options =>    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddHealthChecks()    .AddDbContextCheck<ApplicationDbContext>("sqlserver"); var app = builder.Build(); app.MapHealthChecks("/health"); app.MapControllers(); app.Run();

Add the Entity Framework Core health checks package if it is not already referenced:

dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore

Because this check uses the application's DbContext, the endpoint verifies database connectivity as well as process availability. Do not expose connection strings, SQL statements, stack traces, or sensitive exception details through a public health endpoint.

4. Controlling startup with depends_on

Now configure the API so that it starts only after SQL Server becomes healthy:

services:  api:    build:      context: .      dockerfile: Dockerfile    environment:      ASPNETCORE_ENVIRONMENT: Development      ConnectionStrings__DefaultConnection: "Server=db,1433;Database=CourseDb;User Id=sa;Password=${SA_PASSWORD};TrustServerCertificate=True;"    ports:      - "8080:8080"    depends_on:      db:        condition: service_healthy  db:    image: mcr.microsoft.com/mssql/server:2022-latest    environment:      ACCEPT_EULA: "Y"      MSSQL_PID: "Developer"      MSSQL_SA_PASSWORD: "${SA_PASSWORD}"    volumes:      - sqlserver-data:/var/opt/mssql    healthcheck:      test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -C -Q \"SELECT 1\" -b -o /dev/null"]      interval: 10s      timeout: 5s      retries: 12      start_period: 30s volumes:  sqlserver-data:

With this configuration, Compose waits until the SQL Server health check succeeds before creating the API container. This is a startup dependency, not a complete runtime recovery strategy. If the database later becomes unavailable, the application still needs appropriate connection timeouts, retry behavior, and error handling.

5. Running migrations as a separate service

Applying migrations during API startup can be convenient in development. In production, however, multiple API instances may attempt to update the schema at the same time, the application identity may need excessive database permissions, and migration work may delay application startup. A separate deployment step is usually easier to control and audit.

In this example, the migration service reuses the API image. When the application receives the --migrate argument, it applies migrations and exits:

var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<ApplicationDbContext>(options =>    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); var app = builder.Build(); if (args.Contains("--migrate")) {    await using var scope = app.Services.CreateAsyncScope();    var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();    await db.Database.MigrateAsync();    Console.WriteLine("Database migration completed successfully.");    return; } app.MapHealthChecks("/health"); app.MapControllers(); await app.RunAsync();

In a production-quality application, consider moving the migration workflow into a dedicated class or console project. The important behavior is that the migration process returns exit code zero on success and a nonzero exit code on failure.

Add the one-time service and make the API depend on its successful completion:

services:  migrate:    build:      context: .      dockerfile: Dockerfile    command: ["dotnet", "CourseApi.dll", "--migrate"]    environment:      ConnectionStrings__DefaultConnection: "Server=db,1433;Database=CourseDb;User Id=sa;Password=${SA_PASSWORD};TrustServerCertificate=True;"    depends_on:      db:        condition: service_healthy  api:    build:      context: .      dockerfile: Dockerfile    environment:      ASPNETCORE_ENVIRONMENT: Development      ConnectionStrings__DefaultConnection: "Server=db,1433;Database=CourseDb;User Id=sa;Password=${SA_PASSWORD};TrustServerCertificate=True;"    ports:      - "8080:8080"    depends_on:      db:        condition: service_healthy      migrate:        condition: service_completed_successfully

The sequence is now explicit: SQL Server becomes healthy, the migration service runs, and the API starts only if migration exits successfully. If the migration fails, the API is not started and the error remains visible instead of being hidden by a partially initialized application.

6. Verifying readiness through logs

Start the stack with:

docker compose up --build

Use another terminal to inspect service status and health information:

docker compose ps docker inspect --format='{{json .State.Health}}' $(docker compose ps -q db) docker compose logs -f db migrate api

The expected sequence is SQL Server initialization, a successful migration message, and then API startup. Test the API readiness endpoint:

curl http://localhost:8080/health

A successful health check normally returns HTTP 200. If the database check fails, the API health endpoint should return a failure status. If migration fails, docker compose ps will usually show the migration container as Exited (1).

Common mistakes

  • Confusing host ports with service names: Inside the Compose network, the API connects to db, not localhost. The host mapping 1433 is for clients outside the Compose network.
  • Treating depends_on as a retry mechanism: service_healthy controls startup. It does not automatically repair every connection failure after the application is running.
  • Using the wrong variable expansion: Use $$MSSQL_SA_PASSWORD inside the health check so the password is resolved in the container.
  • Keeping the migration service alive forever: The migration process must finish. Running a web server from the migration service prevents service_completed_successfully from being satisfied.
  • Granting schema permissions to the application identity: For production, consider a separate deployment identity, reviewed SQL scripts, or an EF Core migration bundle.

Practice exercise

  1. Add a SQL Server health check to your existing Compose file.
  2. Expose an ASP.NET Core /health endpoint that checks the database.
  3. Create a one-shot service named migrate.
  4. Configure the API to wait for the migration service to complete successfully.
  5. Temporarily change the health check password and observe the unhealthy state.
  6. Write down the expected order of the DB, migration, and API log messages.

Conclusion

This lesson showed why a running container is not necessarily a ready service. We defined a query-based SQL Server health check, used the Compose conditions service_healthy and service_completed_successfully, and automated EF Core migrations through a separate service. The result is a more predictable development startup process and a clear foundation for controlled migration execution during production deployment.

Sources