LESSON 11 OF 14

11. Running the API and SQL Server Together with Docker Compose

In this lesson, you will combine the ASP.NET Core API, SQL Server, network, and volume definitions in one docker-compose.yml file and manage the complete system with a single command.

60 dk 67

Introduction

In the previous lessons, you ran the ASP.NET Core API in a container, created a SQL Server container, managed environment variables and connection strings, and worked with networks, volumes, and Entity Framework Core migrations. This lesson brings those pieces together in one Compose-based application stack.

Docker Compose is a declarative tool for defining how multiple containers should be created, which images they should use, how ports should be published, which networks they should join, and where persistent data should be stored. Instead of repeatedly typing long docker run commands, you can manage the complete environment from a YAML file stored next to the project.

Our application will contain two services: an ASP.NET Core service named api and a SQL Server service named sqlserver. The API will connect to SQL Server through the Compose service name sqlserver, not through localhost. SQL Server data will be persisted in a named volume called sqlserver_data.

The role of a Docker Compose file

A Dockerfile describes how to build one application image. A Compose file describes how multiple containers should be run and connected. In other words, the Dockerfile explains the image-building process, while Compose defines the runtime environment.

Current Docker Compose installations support both compose.yaml and docker-compose.yml. This lesson uses the requested filename, docker-compose.yml. Compose treats the directory containing the file as the default project directory and uses the project name when naming containers, networks, and volumes.

Preparing the project structure

Assume that the solution has the following structure:

DockerStore.sln src/  Store.Api/    Store.Api.csproj    Program.cs    Dockerfile    appsettings.json    appsettings.Development.json .dockerignore docker-compose.yml

We assume that the multi-stage Dockerfile created in the previous lesson is located in src/Store.Api and that the application listens on port 8080 inside the container. If your application uses another port, adjust the port mappings and environment values accordingly.

Creating the initial Compose configuration

Create docker-compose.yml in the solution root:

services:  api:    build:      context: .      dockerfile: src/Store.Api/Dockerfile    ports:      - "8080:8080"    environment:      ASPNETCORE_ENVIRONMENT: Production      ASPNETCORE_URLS: http://+:8080      ConnectionStrings__DefaultConnection: Server=sqlserver,1433;Database=StoreDb;User Id=sa;Password=${SQLSERVER_SA_PASSWORD};TrustServerCertificate=True;MultipleActiveResultSets=True    depends_on:      - sqlserver    networks:      - store-network  sqlserver:    image: mcr.microsoft.com/mssql/server:2022-latest    environment:      ACCEPT_EULA: "Y"      MSSQL_SA_PASSWORD: ${SQLSERVER_SA_PASSWORD}    ports:      - "1433:1433"    volumes:      - sqlserver_data:/var/opt/mssql    networks:      - store-network volumes:  sqlserver_data: networks:  store-network:    driver: bridge

The top-level services section defines the services to run. The volumes section defines persistent storage, and the networks section defines the communication network used by the services.

Understanding build and context

The api service builds an image from a Dockerfile instead of using a prebuilt image. context: . selects the solution root as the build context. This is important when the Dockerfile copies the solution file or references other projects. The context should not be limited to src/Store.Api in that case.

The dockerfile property explicitly identifies the Dockerfile location. Because the Compose file is in the solution root, the path is src/Store.Api/Dockerfile.

Understanding ports

The mapping "8080:8080" connects port 8080 on the host to port 8080 inside the API container. A request to http://localhost:8080 is forwarded to the application listening inside the container.

Publishing port 1433 for SQL Server is useful during development when you want to connect from SSMS, Azure Data Studio, or another tool running on the host. The API container does not use this host port to reach SQL Server. It uses sqlserver:1433 through the internal Compose network.

Understanding environment and connection strings

The environment variable ConnectionStrings__DefaultConnection maps to the ASP.NET Core configuration key ConnectionStrings:DefaultConnection. The double underscore represents a hierarchy separator, so the value can be read with builder.Configuration.GetConnectionString("DefaultConnection").

The server portion of the connection string is Server=sqlserver,1433. The hostname sqlserver is the service name. Using localhost here is a common mistake because localhost inside the API container refers to the API container itself, not the SQL Server container.

Understanding depends_on

depends_on tells Compose that the API service depends on the SQL Server service and should be started after it. However, this does not guarantee that the SQL Server engine is already ready to accept connections. SQL Server may need several seconds after the container starts before the database engine is available.

For real applications, consider combining startup dependencies with a health check, application-level retry logic, or a controlled migration step. The goal of this lesson is to establish the basic Compose orchestration; readiness handling can be expanded as part of deployment design.

Understanding volumes and networks

The mapping sqlserver_data:/var/opt/mssql stores SQL Server's data directory in a named volume. The database files remain available as long as the volume is not removed, even if the SQL Server container is recreated.

We explicitly define a bridge network named store-network. Compose can create an implicit default network, but an explicit network makes the communication boundary visible in the project configuration. Since both services join the same network, they can discover each other by service name.

Managing the password with a .env file

Instead of writing the password directly in the Compose file, create a .env file in the solution root:

SQLSERVER_SA_PASSWORD=Str0ng_Local_Password_2026!

Compose resolves ${SQLSERVER_SA_PASSWORD} from this file. Do not commit .env to a Git repository in a real project. Add it to .gitignore:

.env

The password must satisfy SQL Server password complexity requirements. A short password or a password containing only letters may prevent the SQL Server container from starting. In production, use a secure secret management solution instead of placing credentials in source code, Compose files, or log output.

Building and starting the stack

From the solution root, validate the Compose model:

docker compose config

This command checks the YAML structure and resolves environment variables. Remember that sensitive values may appear in the terminal output.

Start the stack in attached mode for the first run:

docker compose up --build

The --build option rebuilds the API image from the Dockerfile. If the SQL Server image is not available locally, Docker pulls it. Compose creates the network, prepares the volume, and starts the service containers.

To run the stack in the background:

docker compose up --build -d

List the service status with:

docker compose ps

Follow logs for all services:

docker compose logs -f

Follow only the API logs:

docker compose logs -f api

Test the API at http://localhost:8080. If Swagger is enabled, you can also open http://localhost:8080/swagger.

Running migrations

The previous lesson covered migration management. Running an Entity Framework Core migration inside the API container requires the image to include the .NET SDK and the Entity Framework tools. A production multi-stage image may contain only the runtime and therefore may not include dotnet ef.

For development, you can run migrations from the host, but the connection string must use the host-facing address. From the host, SQL Server is normally reached through localhost,1433. From the API container, the correct address remains sqlserver,1433.

Another option is to use a separate SDK-based tools container or a dedicated migration job. Automatically running migrations every time the API container starts can cause locking and concurrent migration problems, especially in production, so the strategy should be designed deliberately.

Stopping, restarting, and cleaning up

Stop the services without removing the containers:

docker compose stop

Start previously stopped containers with:

docker compose start

Stop and remove the containers and Compose-created networks with:

docker compose down

To remove the named volumes as well:

docker compose down -v

Be careful: down -v permanently removes the SQL Server data stored in the named volume. Use it only when you intentionally want to reset the development database or clean up a test environment.

Common mistakes

  • Using localhost from the API: Inside a container, localhost points to that container. Use the sqlserver service name in the connection string.
  • Confusing host and container ports: The API does not need the published host port to reach SQL Server. It uses sqlserver:1433 on the internal network.
  • Using the wrong build context: A Dockerfile that references the solution or other projects needs the solution root as its build context.
  • Typing the environment variable incorrectly: Use ConnectionStrings__DefaultConnection with two underscores for ASP.NET Core hierarchical configuration.
  • Treating depends_on as a readiness check: Startup order and application readiness are different concerns.
  • Deleting the volume accidentally: docker compose down -v removes database data.
  • Using invalid YAML indentation: Do not use tab characters in YAML, and quote port mappings such as "8080:8080".

Practice exercise

Complete the following exercise in your own project:

  1. Add the API and SQL Server services to a Compose file.
  2. Define the sqlserver_data named volume for SQL Server.
  3. Attach both services to the store-network network.
  4. Verify that the connection string uses sqlserver as the server name.
  5. Validate the configuration with docker compose config.
  6. Start the stack using docker compose up --build -d.
  7. Inspect the state with docker compose ps and docker compose logs api.
  8. Create a record through the API, then run docker compose down followed by docker compose up -d.
  9. Confirm that the record still exists. Finally, only in the test environment, run docker compose down -v and observe that the data is removed.

Conclusion

In this lesson, you combined the API and SQL Server services in one Docker Compose configuration. You centralized image building with build, host access with ports, runtime configuration with environment, service dependency with depends_on, persistent database storage with a named volume, and service communication with a dedicated network.

You can now start the complete system with docker compose up, inspect it with docker compose logs, and stop it with docker compose down instead of maintaining a collection of error-prone manual commands. The next step is to separate development and production configuration and improve the stack with health checks, secure secret handling, and deployment-oriented settings.

Sources