.NET › Docker & Containerization

How do you pass environment-specific configuration into a running .NET container, and how does this interact with the configuration system?

Intermediate

Answer

Environment variables passed to a container (via `docker run -e`, a Docker Compose environment section, or a Kubernetes deployment's env field) are automatically picked up by ASP.NET Core's environment variable configuration provider using the double-underscore convention for nested keys, letting you fully configure a container's behavior at deploy time without rebuilding the image or baking environment-specific settings into it.
docker run -e ConnectionStrings__Db="Server=prod-db;..." -e ASPNETCORE_ENVIRONMENT=Production myapp:latest

# Or in Kubernetes:
env:
  - name: ConnectionStrings__Db
    valueFrom: { secretKeyRef: { name: db-secret, key: connection-string } }
Real-world example The exact same Docker image is deployed to dev, staging, and production Kubernetes clusters, with each environment's specific connection strings and feature flags injected purely through environment variables, honoring the 'build once, deploy everywhere' principle.

Common follow-ups: How do you handle secrets specifically (versus regular config) in a Kubernetes environment variable setup?;What ASPNETCORE_ENVIRONMENT value should each deployment tier use?