Introduction
Environment variables are one of the simplest and most common ways to pass configuration and runtime settings into applications. In microservices architectures — where you run many small services independently (often in containers) — environment variables let you decouple configuration from code so the same build can run in dev, staging, and production with different behavior.
This article explains what environment variables are, how they’re used inside microservices, and concrete examples (Docker, Kubernetes, .NET). It also covers security, best practices, and troubleshooting.
What is an environment variable?
An environment variable is a named value provided by the operating environment (OS, container runtime, orchestrator) that an application can read at runtime. Examples:
-
DATABASE_URL=postgres://user:pass@db:5432/mydb
-
ASPNETCORE_ENVIRONMENT=Production
-
API_KEY=xyz
Key idea: configuration via environment variables means code doesn’t need to change across deployments — only the environment/table of variables changes.
Why microservices use environment variables
-
Separation of config and code — same build artifact, different environment settings.
-
12-Factor app compliance — environment variables are one of the 12-factor recommendations for config.
-
Container friendliness — Docker, Kubernetes and serverless platforms natively support env vars.
-
Simplicity — easy to set and read from any language/runtime.
-
Integration with orchestration — k8s
ConfigMap
/Secret
, cloud config services map nicely to env vars.
Types of configuration you usually store in env vars
-
Connection strings and endpoints (
DB_HOST
,REDIS_URL
) -
Feature flags and mode (
FEATURE_X_ENABLED=true
,ENV=staging
) -
API keys and short-lived tokens (preferably via secrets manager)
-
Service-specific settings (
MAX_WORKERS=5
,LOG_LEVEL=info
)
Note: For long-term secrets, prefer a secret manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault) or k8s Secrets — see security section.
How to provide environment variables to microservices
1. Docker (local / containers)
-
docker run -e NAME=value image
-
docker run --env-file .env image
-
Dockerfile
ENV
instruction (bakes into image; generally avoid storing secrets in image)
Example docker run
:
2. Docker Compose
docker-compose.yml
:
.env
file:
3. Kubernetes (ConfigMap and Secret)
-
ConfigMap
for non-sensitive config. -
Secret
for sensitive data (note: k8s Secrets are base64 encoded by default; enable encryption at rest).
Example Deployment
using env from ConfigMap
and Secret
:
Or explicit env mapping:
4. Cloud platforms
-
Azure App Service / AWS ECS / GCP Cloud Run: allow setting app settings / environment variables in the platform UI or IaC (ARM, CloudFormation, Terraform).
-
Use cloud secret integrations to inject secrets as env vars or mounted files.
5. CI/CD pipelines
Inject environment variables during builds or deploys (GitHub Actions env
, Azure Pipelines variables
, GitLab CI variables
), but avoid putting secrets in plain logs.
How to read environment variables inside microservices
.NET (ASP.NET Core / .NET 6+)
ASP.NET Core integrates environment variables into IConfiguration
automatically when using the default WebHost/Host builder. Example minimal API:
Directly via Environment
:
Important: .NET configuration supports double-underscore mapping to nested keys — ConnectionStrings__Default
-> ConnectionStrings:Default
.
Node.js
Java (Spring Boot)
Spring Boot reads env vars automatically into configuration properties — or use @Value("${DB_HOST}")
.
Examples — end-to-end
Example: Containerized .NET microservice using Docker + env vars
-
Build image:
-
Run with env:
-
In code the config is available via
builder.Configuration["ConnectionStrings:Default"]
.
Example: Kubernetes config + secret usage
-
kubectl create configmap my-config --from-literal=LOG_LEVEL=info
-
kubectl create secret generic my-secret --from-literal=DB_PASSWORD=supersecret
-
Deployment uses
envFrom
as shown earlier.
Best practices and patterns
Follow the 12-factor app pattern
-
Store config in the environment; do not hard-code environment-specific settings.
Prefer platform secret stores for sensitive data
-
Use HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or k8s providers (external secrets) to deliver secrets safely.
-
Inject secrets at runtime — either as env vars or mounted files.
Use distinct variables for environment and secrets
-
ASPNETCORE_ENVIRONMENT=Development|Staging|Production
-
DB_CONNECTIONSTRING
, notDB_USERPASS
in code.
Don’t log secrets
-
Ensure logging/configuration doesn’t print raw env vars.
Use typed configuration and validation
-
In .NET, bind configuration to strongly-typed options and validate on startup (IOptions with Data Annotations or custom validation). Fail fast if required config missing.
Minimize env var surface
-
Only expose what service needs. Keep variable names consistent across services.
Namespacing and conventions
-
Prefix variables per service or team:
PAYMENTS_DB_HOST
vsORDERS_DB_HOST
.
Rotation and revocation
-
Plan for secret rotation; short-lived tokens are safer than long-lived credentials.
Use files for very large secrets
-
Some platforms mount secrets as files (e.g., Docker secrets, k8s secrets volume). Reading from files may be more secure for large certs.
Security considerations & caveats
-
Env vars are visible to the process and can be leaked via process dumps or certain debugging tools. They also appear to any user who can inspect the process environment (on some systems).
-
Kubernetes Secrets are base64-encoded — enable encryption at rest or use an external secrets manager for production.
-
Do not store secrets in source control including
Dockerfile
ENV
instructions containing passwords. -
Least privilege: container/pod/service account should have minimal permissions to retrieve secrets.
-
Audit and monitor access to secret stores.
Troubleshooting tips
-
Confirm env var exists:
printenv
inside container orkubectl exec -it pod -- printenv
. -
Check precedence: in many stacks, command-line args > env vars > config files. Know your framework’s precedence rules.
-
For .NET: check for
__
vs:
mapping (ConnectionStrings__Default
). -
Avoid trailing spaces/newlines in values from secrets — they can break connection strings.
Quick checklist before production rollout
-
All required variables documented and validated at startup.
-
Secrets delivered via secure secret manager; not baked into images.
-
Access to secrets restricted and audited.
-
CI/CD injects env vars securely (pipeline secrets).
-
Health checks and log redaction in place.
-
Config matches the environment (
ASPNETCORE_ENVIRONMENT
etc).
Summary
Environment variables are a simple, platform-friendly way to configure microservices without changing code. They work exceptionally well in containerized and orchestrated environments (Docker, Kubernetes), but handling secrets requires care: use managed secret stores, follow the 12-factor approach, and validate configuration at startup. For .NET developers, IConfiguration
+ environment providers and Environment.GetEnvironmentVariable
are the standard ways to access variables; remember the double-underscore convention for nested keys.
No comments:
Post a Comment