I have an ASP.NET Core 6 Web API (User.API
) that I’m trying to run in a Docker container, alongside a separate SQL Server container. My goal is to deploy these containers on a friend’s machine without requiring them to install .NET Core or SQL Server. Even though SQL Server seems to start correctly, my API keeps failing to connect to it.
Here is my docker-compose.yml:
version: '1.0'
services:
userapi:
image: userapi
build:
context: .
dockerfile: User.API/Dockerfile
ports:
- "5000:80"
environment:
- ConnectionStrings__UserDbConnection=Server=sqlserver;Database=UserDB;User=sa;Password=YourPassword123;
depends_on:
- sqlserver
sqlserver:
image: mcr.microsoft.com/mssql/server
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=YourPassword123
ports:
- "1433:1433"
And a snippet from my Dockerfile for the API:
# Use the official image as a parent image
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
...
# Use the SDK image to build the app
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["User.API/User.API.csproj", "User.API/"]
...
The API continually throws this error:
Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904):
A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible.
Things I’ve tried:
- Ensuring SQL Server is fully initialized before the API tries to connect. The SQL Server logs indicate it is ready to accept connections.
- Double-checking the connection string in the API. It is using the service name (sqlserver) from the docker-compose.yml as the server name.
- Attempting to add retry logic to the API to wait for SQL Server to be ready.
- The SQL Server container logs indicate that it is running and ready to accept connections, but the API cannot seem to connect to it no matter what I try.
Any help would be greatly appreciated!
2
Answers
Sherif Elmetainy recommended altering the server's port to 1433, and after implementing this change, it proved effective. It's essential to emphasize that a robust password is a prerequisite for the proper establishment of this connection.
Try changing the connection string to indicate using tcp protocol
Normally this should use the default port, but you can try with explicitly specifying port number