Introduction
In the previous lessons, we ran the ASP.NET Core API and SQL Server together with Docker Compose, managed connection values through environment variables, and moved migration operations into the container workflow. Although the application works, keeping development and production behavior in one configuration creates long-term problems.
Swagger UI, detailed exception pages, source-code mounts, hot reload, and verbose logs are useful during development. Production requires a smaller image, controlled logging, protected error responses, secure secret handling, centralized HTTPS termination, and fewer development tools. In this lesson, we will use separate configuration layers for the same project.
Why separate development and production?
An application's environment is not only a different database address. The following behaviors may also vary:
- Development: Swagger UI is enabled, detailed exception information is available, source code may be mounted as a volume, and developer-friendly logging is used.
- Production: Swagger is disabled unless explicitly enabled, exception details are not returned to clients, only the runtime image is deployed, and secrets are not committed to source control.
- HTTPS: A local certificate may be used during development. In production, TLS is commonly terminated by a reverse proxy, ingress controller, or cloud load balancer.
- Data: A development database can often be recreated, while production data must be stored in a persistent volume or a managed SQL Server service.
ASP.NET Core uses the ASPNETCORE_ENVIRONMENT variable to determine the current environment. Common values are Development, Staging, and Production. The application also loads appsettings.json and the environment-specific appsettings.{Environment}.json file.
Recommended project structure
We will keep the API and SQL Server service names used in the previous lessons. A sample structure is:
DockerCourse.Api/ ├── Dockerfile ├── compose.yaml ├── compose.dev.yaml ├── compose.prod.yaml ├── .env.development ├── .env.production.example ├── src/ │ └── DockerCourse.Api/ │ ├── Program.cs │ ├── appsettings.json │ ├── appsettings.Development.json │ └── appsettings.Production.json └── secrets/ └── README.md
compose.yaml contains shared service definitions, compose.dev.yaml contains development overrides, and compose.prod.yaml contains production overrides. When multiple Compose files are supplied, later files override compatible values from earlier files or add new configuration.
Creating the shared Compose file
First, define the services shared by both environments:
services: api: build: context: . dockerfile: Dockerfile depends_on: sqlserver: condition: service_healthy environment: ConnectionStrings__DefaultConnection: ${CONNECTIONSTRINGS__DEFAULTCONNECTION} ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 ports: - "8080:8080" sqlserver: image: mcr.microsoft.com/mssql/server:2022-latest environment: ACCEPT_EULA: "Y" MSSQL_PID: ${MSSQL_PID:-Developer} MSSQL_SA_PASSWORD: ${MSSQL_SA_PASSWORD} volumes: - sqlserver-data:/var/opt/mssql healthcheck: test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P \"$${MSSQL_SA_PASSWORD}\" -C -Q \"SELECT 1\" || exit 1"] interval: 10s timeout: 5s retries: 10 volumes: sqlserver-data:
The double underscore in ConnectionStrings__DefaultConnection represents the ConnectionStrings:DefaultConnection key to the ASP.NET Core configuration provider. Instead of hard-coding a connection string in the Compose file, the value is supplied by the selected environment file.
Development configuration
During development, we may want to mount source code, enable Swagger, and increase log detail:
services: api: environment: ASPNETCORE_ENVIRONMENT: Development Logging__LogLevel__Default: Debug Logging__LogLevel__Microsoft.AspNetCore: Information volumes: - ./src/DockerCourse.Api:/src ports: - "8080:8080" - "8443:8443" sqlserver: environment: MSSQL_PID: Developer
The source-code volume shown here does not automatically rebuild binaries inside the container. To use hot reload, create a separate development Dockerfile target or design a workflow that runs dotnet watch on the host or in a development container. Do not copy this volume into the production Compose file.
A possible .env.development file is:
ASPNETCORE_ENVIRONMENT=Development MSSQL_PID=Developer MSSQL_SA_PASSWORD=LocalOnly_StrongPassword_123! CONNECTIONSTRINGS__DEFAULTCONNECTION=Server=sqlserver,1433;Database=DockerCourseDb;User Id=sa;Password=LocalOnly_StrongPassword_123!;TrustServerCertificate=True
This file is suitable for local development, but real production passwords must not be stored here or committed to a Git repository.
Production configuration
The production Compose file should not contain development-only volumes, debug settings, or unnecessary published ports:
services: api: environment: ASPNETCORE_ENVIRONMENT: Production Logging__LogLevel__Default: Information Logging__LogLevel__Microsoft.AspNetCore: Warning restart: unless-stopped read_only: true tmpfs: - /tmp sqlserver: environment: MSSQL_PID: ${MSSQL_PID} restart: unless-stopped
read_only: true prevents the application from writing to the container filesystem. If the application creates temporary files, provide writable storage only for the required paths through a volume or tmpfs. Not every application is immediately compatible with this setting, so logging, Data Protection keys, and temporary-file behavior should be tested before production deployment.
Instead of hard-coding production secrets in compose.prod.yaml, use a CI/CD secret store, a deployment platform's secret mechanism, or an external secret manager. A local example file may look like this:
# .env.production.example ASPNETCORE_ENVIRONMENT=Production MSSQL_PID=Express MSSQL_SA_PASSWORD=REPLACE_WITH_SECRET CONNECTIONSTRINGS__DEFAULTCONNECTION=Server=sqlserver,1433;Database=DockerCourseDb;User Id=sa;Password=REPLACE_WITH_SECRET;TrustServerCertificate=True
.env.production.example should contain only variable names and placeholders. The real .env.production file must be excluded through .gitignore.
Separating ASP.NET Core configuration sources
Shared settings belong in appsettings.json:
{ "AllowedHosts": "*", "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } } }
The development file can improve the developer experience:
{ "Logging": { "LogLevel": { "Default": "Debug", "Microsoft.AspNetCore": "Information" } }, "Features": { "EnableSwagger": true } }
The production file can use more controlled logging and disable Swagger:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Microsoft.EntityFrameworkCore.Database.Command": "Warning" } }, "Features": { "EnableSwagger": false } }
Use the environment and feature setting in Program.cs:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); var enableSwagger = app.Configuration.GetValue("Features:EnableSwagger"); if (app.Environment.IsDevelopment() || enableSwagger) { app.UseSwagger(); app.UseSwaggerUI(); } if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/error"); app.UseHsts(); } app.UseHttpsRedirection(); app.MapControllers(); app.Run();
If an HTTPS certificate has not been configured inside the container, UseHttpsRedirection can cause unexpected redirects. When TLS is terminated by a reverse proxy, it can be preferable for the application to listen on HTTP inside the private network while the proxy handles HTTPS. The correct choice depends on the deployment architecture.
Running the Compose configurations
Start the development environment with:
docker compose \ --env-file .env.development \ -f compose.yaml \ -f compose.dev.yaml \ up --build
Start a production-like environment with:
docker compose \ --env-file .env.production \ -f compose.yaml \ -f compose.prod.yaml \ up -d --build
Before starting, inspect the final merged Compose configuration:
docker compose \ --env-file .env.production \ -f compose.yaml \ -f compose.prod.yaml \ config
This command helps verify variable interpolation, production volume settings, and the final port configuration.
Common mistakes
- Enabling Swagger unconditionally in production: Swagger is not automatically a vulnerability, but it can expose the endpoint surface unnecessarily. Keep it disabled by default.
- Copying secrets into the image: Using ENV, COPY, or build arguments in a Dockerfile can leave secrets in image layers or build history. Provide secrets at runtime.
- Using the wrong environment variable name: For hierarchical ASP.NET Core settings in Linux containers, use __ instead of :.
- Assuming paths are relative to the second Compose file: With multiple Compose files, relative paths are evaluated from the location of the first Compose file.
- Carrying a development volume into production: Mounting source code in production reduces image reproducibility and weakens isolation.
- Increasing log levels without limits: Debug logs may expose connection strings or sensitive request data and can significantly increase storage costs.
Short practice exercise
- Create compose.yaml, compose.dev.yaml, and compose.prod.yaml.
- Enable Swagger, Debug logging, and the source-code volume in the development override.
- Remove that volume from production, set the log level to Information, and try running the API container as read-only.
- Set Features:EnableSwagger to true in appsettings.Development.json and false in the production file.
- Inspect both merged configurations with docker compose config.
- Confirm that Swagger is reachable in development and disabled in the production-like environment.
Conclusion
In this lesson, we separated development and production configurations using Compose override files, environment files, and ASP.NET Core configuration sources. Swagger, verbose logging, source-code mounts, and debugging conveniences remain in development instead of being carried into the production image. Production uses controlled logging, a runtime-focused image, externally supplied secrets, and, where compatible, a read-only filesystem.
In the next step, this separation can be connected to deployment workflows, image tagging, and publishing strategies in a more systematic way.
Sources
- https://learn.microsoft.com/aspnet/core/fundamentals/environments?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/index?tabs=basicconfiguration
- https://docs.docker.com/compose/how-tos/environment-variables/set-environment-variables/
- https://docs.docker.com/reference/cli/docker/compose
- https://docs.docker.com/build/building/best-practices/