LESSON 7 OF 14

7. Managing Environment Variables and Connection Strings

Move the ASP.NET Core connection string out of source code and configure the API securely through appsettings, environment variables, and Docker Compose.

50 dk 66

Introduction

Writing database connection details directly into an ASP.NET Core application may seem convenient at first. However, this approach quickly becomes difficult to maintain when the application moves into containers. Development, testing, and production environments may use different SQL Server hosts, credentials, and passwords. Hard-coding those values increases maintenance effort and can expose sensitive information in source control.

In this lesson, we will connect the ProductApi ASP.NET Core Web API to the sqlserver service created in the previous lesson. We will read the connection string from appsettings.json, then override it through Docker Compose environment variables. As a result, the same application image can run in multiple environments without being rebuilt.

How ASP.NET Core configuration works

ASP.NET Core does not rely on a single configuration file. Multiple providers can be combined, including JSON files, environment variables, user secrets, and command-line arguments. In the default configuration, a provider loaded later can override an earlier value when both providers contain the same key.

The following priority order is useful in practice:

  1. appsettings.json provides general defaults.
  2. appsettings.{Environment}.json provides environment-specific overrides.
  3. User secrets can be used while running in the Development environment.
  4. Environment variables can override JSON and user-secret values.
  5. Command-line values generally have the highest priority.

This model allows non-sensitive defaults to remain in files while real passwords are supplied at runtime. When hierarchical configuration keys are represented as environment variables, use a double underscore. For example, the ConnectionStrings:DefaultConnection key becomes ConnectionStrings__DefaultConnection as an environment variable.

Moving the connection string into appsettings

First, make sure the database registration reads a named configuration value. Update the Program.cs file as follows:

var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")    ?? throw new InvalidOperationException(        "The DefaultConnection connection string was not found."); builder.Services.AddDbContext<AppDbContext>(options =>    options.UseSqlServer(connectionString)); builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();

GetConnectionString("DefaultConnection") looks for the ConnectionStrings:DefaultConnection key. Failing immediately with a clear error is preferable to allowing the application to continue until it produces an ambiguous database connection exception.

For a locally running application, appsettings.Development.json might contain the following value:

{  "ConnectionStrings": {    "DefaultConnection": "Server=localhost,1433;Database=AppDb;User Id=sa;Password=LocalOnly_123!;TrustServerCertificate=True;Encrypt=False"  } }

This file should be limited to local development. Do not place a real production password in it or commit it to source control. A better approach is to use .NET User Secrets during development or keep a sample configuration file that contains no real credentials.

Using the correct server name inside Docker

Inside an application container, localhost does not refer to the SQL Server container. It refers to the API container itself. On a Compose network, services reach one another by service name. Therefore, the API container must use sqlserver as the database host.

The following connection string works when both containers are attached to the same Compose network:

Server=sqlserver,1433;Database=AppDb;User Id=sa;Password=...;TrustServerCertificate=True;Encrypt=False

Here, sqlserver is the service name in the Compose file. Port 1433 is the SQL Server port inside the container. Even if a different host port is mapped, container-to-container communication uses the container port. For example, if the host mapping is 14330:1433, a connection from your computer uses localhost,14330, while a connection from the API container uses sqlserver,1433.

Passing environment variables with Docker Compose

Now define the API and SQL Server services in one Compose file. In this example, the api service receives its connection string through an environment variable:

services:  sqlserver:    image: mcr.microsoft.com/mssql/server:2022-latest    environment:      ACCEPT_EULA: "Y"      MSSQL_SA_PASSWORD: ${SA_PASSWORD:?SA_PASSWORD must be set}    ports:      - "14330:1433"    volumes:      - sqlserver-data:/var/opt/mssql  api:    build:      context: .      dockerfile: ProductApi/Dockerfile    environment:      ASPNETCORE_ENVIRONMENT: Production      ASPNETCORE_URLS: http://+:8080      ConnectionStrings__DefaultConnection: "Server=sqlserver,1433;Database=AppDb;User Id=sa;Password=${SA_PASSWORD};TrustServerCertificate=True;Encrypt=False"    ports:      - "8080:8080"    depends_on:      - sqlserver volumes:  sqlserver-data:

The ConnectionStrings__DefaultConnection name is interpreted by ASP.NET Core as ConnectionStrings:DefaultConnection. The ${SA_PASSWORD} expression is resolved by Compose interpolation when the project is started.

Next to the Compose file, create a local-only .env file:

SA_PASSWORD=StrongPassword_123!

Compose may read .env to resolve variables, but those values are not automatically added to the API container's environment. They must be explicitly referenced under the environment section. Add .env to .gitignore.

.env .env.* !.env.example

You can provide teammates with an .env.example file that contains no real password:

SA_PASSWORD=ChangeThisValue_123!

Verifying configuration precedence

To inspect the fully resolved Compose configuration, run:

docker compose config

This command displays the Compose model after variables have been substituted. Because sensitive values may appear in the output, do not share the output without reviewing it first.

After the container starts, you can verify that the environment variable exists inside the container:

docker compose exec api printenv ConnectionStrings__DefaultConnection

Use this command only for troubleshooting. Writing the complete connection string to application logs is unsafe. Prefer logging non-sensitive information such as the database name or server host while masking credentials.

To follow the API logs, run:

docker compose logs -f api

If the API cannot connect, first check whether SQL Server is running and inspect its logs:

docker compose ps docker compose logs sqlserver

depends_on controls service startup order, but it does not guarantee that SQL Server is ready to accept connections. If the application must connect immediately after startup, add retry logic, a healthcheck, or a controlled migration startup strategy.

Managing passwords securely

Using environment variables removes passwords from source code, but it does not solve every security concern. Container environment values may be visible through diagnostic tools and can be accidentally written to logs. In production, evaluate the secret-management features of your deployment platform, Docker secrets, or a centralized store such as Azure Key Vault.

Avoid the following mistakes:

  • Hard-coding a password in appsettings.json, a Dockerfile, or a Compose file.
  • Committing passwords to a Git repository.
  • Printing the connection string in an exception message or debug log.
  • Sharing production credentials in a broadly accessible chat channel.
  • Using the same SA password in every environment.

When a SQL Server container is recreated with a persistent volume, the existing database files and system metadata may be preserved. Therefore, changing MSSQL_SA_PASSWORD later does not necessarily change the SA password associated with the existing data. If a connection fails while reusing a data volume, verify whether the volume was initialized with a different password.

Common mistakes

Using localhost

Using Server=localhost inside the API container attempts to connect to the API container rather than SQL Server. Use the Compose service name, sqlserver in this example.

Using one underscore

ConnectionStrings_DefaultConnection is not the hierarchical key expected by ASP.NET Core. The correct form is ConnectionStrings__DefaultConnection.

Assuming that .env is automatically passed into containers

Compose reading .env for interpolation and passing variables into a container are separate operations. Explicitly reference the variable under environment.

Confusing host and container ports

Keep the host port and container port separate. When the API container connects to SQL Server, it uses the SQL Server service's container port rather than the host-mapped port.

Using special characters in passwords

Semicolons, quotation marks, or Compose interpolation characters in passwords can create YAML and connection-string parsing problems. Use a strong but controlled format in examples, provide production values through a secret mechanism, and never place the real password in sample files.

Practice exercise: Test the configuration

  1. Add a SQL Server password to .env and verify that Git does not track the file.
  2. Define the environment sections for the sqlserver and api services.
  3. Run docker compose config and check for missing variables or YAML errors.
  4. Start the services with docker compose up -d --build.
  5. Inspect status and logs using docker compose ps and docker compose logs api.
  6. Call an API endpoint and verify that Entity Framework Core can access SQL Server.
  7. Temporarily provide an invalid ConnectionStrings__DefaultConnection value and observe the expected connection failure. Restore the correct value afterward.

Conclusion

In this lesson, we examined how ASP.NET Core combines configuration providers and why environment variables are important in containerized applications. We read the connection string with GetConnectionString, used ConnectionStrings__DefaultConnection in the container environment, and connected to SQL Server through the Compose service name instead of localhost.

The main benefit of this approach is that one application image can run in development, testing, and production with different configuration values. In the next stage, we will manage the application and database services together with Docker Compose and connect networking, volumes, healthchecks, and migration workflows to the real project.

Sources