The "Login failed for user 'sa'" error in a Dockerized .NET application usually stems from mismatched connection strings, disabled SQL Server authentication, or network isolation issues. Verify that the SA_PASSWORD environment variable matches your connection string, ensure mixed-mode authentication is enabled in the container, and confirm the host can reach the database port via localhost or the correct container alias.
Verify Connection String Accuracy
The most common cause of this specific authentication failure is an incorrect or malformed connection string within your C# application. When running inside a Docker container, the server address must point to the actual location of the SQL Server instance. If you are using Docker Compose, the hostname in the connection string should match the service name defined in your docker-compose.yml file, not necessarily localhost. For example, if your SQL service is named mssql, the server parameter should be Server=mssql;Database=MyDb;.
Additionally, check for typos in the username and password fields. The user ID must be exactly sa (case-insensitive in SQL Server, but consistency helps), and the password is case-sensitive. Ensure there are no extra spaces or special characters that might have been URL-encoded incorrectly when passed through environment variables. A robust connection string template looks like this:
Data Source=your-sql-server-host;Initial Catalog=YourDatabaseName;User Id=sa;Password=YourStrong!Passw0rd;TrustServerCertificate=True;
If you are using localhost as the data source, remember that it refers to the container itself, not your host machine, unless you have explicitly mapped ports and configured networking accordingly. In many modern setups, using the service name provided by Docker’s internal DNS is more reliable than IP addresses.
Check SQL Server Authentication Mode
By default, some SQL Server images or configurations may only allow Windows Authentication. To use the sa account, Mixed Mode (SQL Server and Windows Authentication) must be enabled. This is typically controlled by the ACCEPT_EULA and SA_PASSWORD environment variables during container initialization, but sometimes the configuration flag needs explicit setting.
Ensure that the MSSQL_LAUNCHER_PASSWORD or similar launcher variables are set correctly if you are using newer versions of the Microsoft SQL Server Docker image. The acceptance of the End User License Agreement (ACCEPT_EULA=Y) is mandatory for the container to start properly. Without this, the SQL Server service might fail to initialize authentication mechanisms entirely, leading to generic login failures.
You can verify the current authentication mode by connecting to the database using a tool like Azure Data Studio or SSMS with a working connection and checking the server properties. Alternatively, you can execute a query against the system view:
SELECT SERVERPROPERTY('IsIntegratedSecurityOnly') AS IsWindowsAuthOnly;
If this returns 1, only Windows Authentication is allowed. You need to restart the container with the appropriate configuration flags to enable mixed mode. This often requires rebuilding the image or ensuring the entrypoint script receives the correct parameters.
Validate Password Complexity and Initialization
SQL Server enforces strict password policies. If the password you provided does not meet complexity requirements (length, uppercase, lowercase, numbers, symbols), the sa account creation may fail silently or result in an inability to log in later. Common mistakes include using simple passwords like password123 without sufficient complexity or forgetting special characters.
When initializing the container, the password is set once. Changing the SA_PASSWORD environment variable after the first run will not update the password because the database files are persisted in volumes. To reset the password, you must either delete the volume (losing data) or connect using a different administrative method to alter the password internally. Always ensure your password meets the criteria: at least 8 characters, not containing the account name, and comprising three of four character classes.
Inspect Network and Port Configuration
Even with correct credentials, network issues can mimic authentication errors. Ensure that the SQL Server container is exposing port 1433 (or your custom port) and that the .NET container can reach it. If both containers are on the same Docker network, they should communicate via service names. If the .NET app is running on the host and trying to connect to the container, you must map the port in docker-compose.yml or docker run commands.
ports:
- "1433:1433"
Use telnet or nc from the .NET container to test connectivity to the SQL server port. If the connection times out, the issue is network-related, not authentication-related. Firewall rules on the host machine can also block inbound connections if the container is exposed to the host network.
Review Application Logs and Exception Details
Sometimes the error message is truncated. Enable detailed logging in your .NET application to capture the full exception stack trace. Look for inner exceptions that might provide more context, such as "TCP Provider: Error code 0x2746" which indicates a network timeout, or specific SQL error codes like 18456. Error sub-statuses in 18456 can tell you exactly why the login failed, such as invalid username or password.
For deeper insights, consider enabling SQL Server error logs within the container. These logs are often accessible via docker logs <container_id> or by mounting a volume to persist them. Analyzing these logs can reveal if the SQL Server instance started successfully and if any security events were triggered during the login attempt.
Frequently Asked Questions
Why does my .NET app work locally but fail in Docker?
This is usually due to differences in how localhost resolves. In Docker, localhost refers to the container itself, so your app cannot reach a SQL Server running on the host unless you use special host-gateway IPs. Use the service name from Docker Compose instead of localhost.
Can I change the SA password after the container starts?
No, changing the environment variable does not update the existing database password. You must connect to the database using an existing admin account and run an ALTER USER command, or recreate the container with a new volume to start fresh.
What if I get Error 18456, State 11?
State 11 typically means the login failed because the password is incorrect or the account is locked. Double-check the password complexity and ensure it matches exactly what was set during container initialization, including special characters.
Is TrustServerCertificate required in .NET 6+?
Yes, modern versions of .NET enforce certificate validation for SQL connections. If your SQL Server uses a self-signed certificate (common in development), you must add TrustServerCertificate=True; to your connection string to avoid handshake failures.
How do I debug if the SQL Server container isn't starting?
Run docker logs <container_name> to see startup errors. Common issues include missing ACCEPT_EULA=Y or insufficient memory allocation. Ensure your host machine has enough RAM allocated to Docker Desktop or your VM engine.