LESSON 8 OF 14

8. Connecting the API and SQL Server with a Docker Network

In this lesson, you will create a custom Docker bridge network, connect the ASP.NET Core API and SQL Server containers, and test communication using the container name.

45 dk 59

Introduction

In the previous lesson, we covered connection strings and environment variable management. However, the server name used in a connection string depends on where the application is running. When the API runs on your computer and SQL Server runs on the host, localhost may be meaningful. When the API and SQL Server run in separate containers, however, localhost refers to the API container itself, not to the SQL Server container.

In this lesson, we will establish communication between the two containers using Docker's user-defined bridge network feature. When the API and SQL Server belong to the same network, Docker can resolve the containers by name. Instead of placing a changeable container IP address in the connection string, we can use the SQL Server container name, sqlserver.

Learning objectives

  • Create a custom Docker bridge network.
  • Attach the SQL Server and ASP.NET Core containers to the same network.
  • Use the container name instead of localhost for inter-container communication.
  • Explain the difference between host ports and container ports.
  • Verify connectivity with docker network inspect, DNS, and port tests.
  • Diagnose common networking and connection string errors.

How does a Docker network work?

Docker can run containers in isolated network environments. The default bridge network is useful for basic scenarios, but user-defined bridge networks are preferable when multiple services need to communicate. They provide better isolation and allow containers on the same network to resolve one another by name through Docker's embedded DNS.

Assume that our application contains the following two containers:

ContainerRoleContainer portExample name
ASP.NET Core APIReceives HTTP requests8080catalog-api
SQL ServerProvides the database service1433sqlserver

The API connects to SQL Server using sqlserver,1433. In this address, sqlserver is the container name resolved by Docker DNS, and 1433 is the port on which SQL Server listens inside its container.

1. Create a custom network

First, create a network named app-net:

docker network create --driver bridge app-net

List the available networks with:

docker network ls

Verify that app-net appears with the bridge driver. The --driver bridge option explicitly selects the default driver for this scenario. For a simple setup, docker network create app-net is also sufficient.

Inspect the network with:

docker network inspect app-net

Because no containers have been attached yet, the Containers section may be empty. Creating a network does not automatically attach containers to it. A container must be connected during creation with --network or later with docker network connect.

2. Attach the SQL Server container to the network

If the SQL Server container from the previous lesson is already running, attach it to the network:

docker network connect app-net sqlserver

Confirm the connection:

docker network inspect app-net

For a clean and repeatable scenario, you can create the container directly on the network. Use a strong password in place of the example value:

docker run -d --name sqlserver \  --network app-net \  -e ACCEPT_EULA=Y \  -e MSSQL_SA_PASSWORD='Str0ngPassword!ChangeMe' \  -p 1433:1433 \  mcr.microsoft.com/mssql/server:2022-latest

The -p 1433:1433 mapping allows the host machine to access SQL Server. The API does not need this host mapping when it is on the same Docker network; it can connect directly to sqlserver:1433. Publishing the port can still be useful for connecting with SSMS or another tool running on the host.

Security note: In real projects, do not leave passwords in command history, source code, or publicly accessible Compose files. Prefer an environment file, Docker secrets, or the secret-management facility of your deployment platform.

3. Attach the API container to the same network

Assume that the API image was built with the multi-stage Dockerfile from earlier lessons and tagged as catalog-api:latest:

docker build -t catalog-api:latest .

Start the API container on the same network:

docker run -d --name catalog-api \  --network app-net \  -p 8080:8080 \  -e ASPNETCORE_URLS=http://+:8080 \  -e ConnectionStrings__Default='Server=sqlserver,1433;Database=CatalogDb;User Id=sa;Password=Str0ngPassword!ChangeMe;TrustServerCertificate=True' \  catalog-api:latest

ASP.NET Core configuration interprets double underscores (__) in environment variable names as hierarchy separators. Therefore, ConnectionStrings__Default represents the ConnectionStrings:Default configuration key.

If your application uses a different connection string key, adjust the example. For example, if the code reads DefaultConnection, the environment variable should be named ConnectionStrings__DefaultConnection.

4. Why does localhost fail?

Inside a container, localhost or 127.0.0.1 refers to that container's own network namespace. If the API container uses Server=localhost,1433, it searches for SQL Server inside the API container. Because SQL Server is running in a different container, the connection fails.

The correct connection string is:

Server=sqlserver,1433;Database=CatalogDb;User Id=sa;Password=...;TrustServerCertificate=True

Here, sqlserver is the name supplied with --name sqlserver when the container was created. Using the container IP address is not recommended. The IP may change when the container is recreated, while the name can remain a stable part of the application design.

5. Verify connectivity with DNS and port tests

First, verify that both containers are running:

docker ps

View the members of the network:

docker network inspect app-net

You should see both sqlserver and catalog-api. If the API image contains a shell, open a shell inside the container:

docker exec -it catalog-api sh

Inside the container, run whichever command is available:

getent hosts sqlserver nslookup sqlserver

Some minimal images do not include ping, nslookup, or getent. The absence of these utilities does not prove that networking is broken. In that situation, start a temporary test container:

docker run --rm -it --network app-net alpine:latest sh

Test DNS resolution from the Alpine container:

getent hosts sqlserver

Test whether the SQL Server TCP port is reachable:

nc -zv sqlserver 1433

A successful result shows that the TCP path to the SQL Server container is open. It does not guarantee that SQL authentication will succeed. The username, password, database name, and SQL Server readiness must also be checked.

6. Diagnose the setup with container inspection

Inspect the network settings of each container:

docker inspect catalog-api docker inspect sqlserver

Search the NetworkSettings and Networks sections for the app-net entry. These sections show the container's IP address on the network, gateway information, and endpoint details associated with the network.

To display only the network information, use:

docker inspect -f '{{json .NetworkSettings.Networks}}' catalog-api

Checking SQL Server logs is also important:

docker logs sqlserver

SQL Server may not accept connections immediately after the container starts. Even if the container appears to be running, the database engine may need several seconds to become ready. If the application runs migrations immediately during startup, this can produce temporary connection failures.

7. Host ports versus container ports

In a port mapping, the value on the left is the host port and the value on the right is the container port:

-p 1401:1433

From the host, you may connect using localhost,1401. From the API container on the same Docker network, you should use sqlserver,1433. Using localhost,1401 from the API is conceptually incorrect and can cause problems in different Docker environments.

Connection sourceCorrect address
SSMS on the hostlocalhost,1433 or the published port
API containersqlserver,1433
Inside the SQL Server containerlocalhost,1433

Common mistakes

The containers are not on the same network

If one of the containers is missing from docker network inspect app-net, name resolution will not work. Attach it with docker network connect app-net container-name.

The wrong container name is used

The name in the connection string must match the actual container name or a network alias. sql-server and sqlserver are different names.

The wrong port is used

Inter-container communication uses the port on which the service listens inside its container, not the host port. For SQL Server, this is usually 1433.

SQL Server is not ready yet

docker ps may show that the container is running while SQL Server is still starting. Check docker logs sqlserver and consider a retry strategy in the application.

The password or database configuration does not match

If the network path works but authentication fails, verify the password, username, and database name in the connection string. When a persistent volume is used, existing SQL Server data may cause newly supplied environment variable values to behave differently than expected.

Practice exercise

  1. Create a user-defined bridge network named training-net.
  2. Attach your SQL Server container to training-net, or create a new container on that network.
  3. Attach the API container to the same network.
  4. Change the connection string from Server=localhost,1433 to Server=sqlserver,1433.
  5. Use docker network inspect training-net to verify that both containers are listed.
  6. Run an Alpine test container and execute getent hosts sqlserver and nc -zv sqlserver 1433.
  7. Send a request to the API through the published host port and verify that the application can access the database.

At the end of the exercise, answer this question: if the SQL Server container were published as 1401:1433, should the API use 1401 or 1433 in its connection string? When the API and SQL Server are on the same Docker network, the correct answer is 1433.

Conclusion

In this lesson, we connected the API and SQL Server containers through a custom Docker bridge network. A user-defined network provides automatic DNS resolution between containers and better isolation. Therefore, the API should use the SQL Server container name instead of a fixed IP address or localhost.

In the next stage, we can express these manual commands with Docker Compose and manage the network, environment variables, volumes, and service startup process from a single configuration file.

Sources