Unable to establish SQL Server connection when deploying ASP.NET app via Docker

I’m having trouble getting my ASP.NET Core 8 application to connect to SQL Server when it runs inside a Docker container. This is my first experience with Docker and .NET together and I’m really struggling.

I have this database utility class that handles migrations:

public static class DatabaseManager
{
    public static async Task HandleDatabaseSetupAsync(IServiceProvider provider, CancellationToken token)
    {
        using var context = provider.GetRequiredService<ApplicationDbContext>();

        var outstandingMigrations = await context.Database.GetPendingMigrationsAsync(token);

        if (outstandingMigrations.Any())
        {
            await context.Database.MigrateAsync(token);
        }
    }
}

The error happens when it tries to check for pending migrations. I get this SQL Server connection error about network issues and the server not being found.

I’ve tried enabling different protocols in SQL Server Configuration Manager and restarting services. I’ve also experimented with various connection string formats like using IP addresses and different instance names but nothing seems to work.

Has anyone successfully connected to a local SQL Server instance from within a Docker container? What am I missing here?

yeah, if ur running the sql server locally, docker sees localhost as its own. try using host.docker.internal in the connection string. also, consider putting sql server in a container too, might simplify things.

what’s your docker setup? docker desktop or linux? and what’s your connection string look like? sometimes it’s not just the host - could be windows auth vs sql auth issues when you’re crossing container boundaries.

Docker containers can’t reach SQL Server using localhost - ran into this exact issue on my first containerized app. Replace localhost or 127.0.0.1 in your connection string with host.docker.internal (Windows/Mac) or 172.17.0.1 (Linux). Make sure SQL Server has TCP/IP connections enabled and the port’s accessible from outside the host. Your container might start before SQL Server’s ready, so add retry logic to your DatabaseManager class. I’d throw in connection timeouts and exponential backoff around those migration checks to handle startup connectivity hiccups.