.net-coretestcontainers

Enabling a container to communicate with SQL Server in a separate container


I have two containers I'm managing with TestContainers in a .NET environment. One container is using MsSqlBuilder like so:

var sqlContainer = new MsSqlBuilder()
            .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
            .WithPassword("Passw0rd#123")
            .WithNetwork(network)
            .WithWaitStrategy(Wait.ForUnixContainer().UntilCommandIsCompleted("/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"Passw0rd#123\" -Q \"SELECT 1\" -b -o /dev/null"))
            .Build();

I have another container running an Azure Function app like so:

var functionContainer = new ContainerBuilder()
            .WithImage(image)
            .WithPortBinding(80, true)
            .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(80), strategy => strategy.WithTimeout(30.Seconds())))
            .WithNetwork(network)
            .WithEnvironment(new Dictionary<string, string>
            {
                { "ConnectionStrings:Notification", notificationConnectionString }
            });

I'm able to launch the Azure Function app, but when I attempt to call an endpoint that communicates with my SQL Server container, I get the following message:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

I am able to communicate with the SQL Server image from my host machine, so I'm sure I'm just missing a network setting. Here's how I am initializing my network:

var network = new NetworkBuilder()
            .WithName(Guid.NewGuid().ToString("D"))
            .Build();

I need to make my Azure Functions container communicate with my SQL Server container, and I thought putting them on the same network would do it. I am able to verify that the connection string is being set properly because I'm able to connect using that same connection string on my host machine.


Solution

  • My issue was caused by not including .WithHostname(hostName) on my SQL Container Builder, and by using a connection string that used 127.0.0.1 instead of that hostName.