Environment variables and configuration: the 12-Factor App explained
What environment variables are, how to set and read them in the terminal, Python, Node, Docker, and Kubernetes, why they don't replace a secrets vault, and what the 12 factors still teach today.
Development$ printenv | sort▍The same code needs to run on your laptop, in staging, and in production. What changes between them? The database address, the log level, the credentials. If those values are written into the code, you have to build a different version for each place, and sooner or later a production password ends up in Git. The classic solution is to separate code from configuration, and the most common way to do that is with environment variables.
What environment variables are
An environment variable is a NAME=value pair that the operating system hands to each program when it starts. Think of a note you slip into someone’s backpack before a trip: the program opens the backpack, reads the note, and adjusts itself, without anyone having to tinker with its insides.
You already use several without noticing: PATH (where the shell looks for commands), HOME (your home folder), and LANG (language). One important detail: a process inherits the variables of whoever started it, and changes made later don’t reach programs that are already running.
Setting and reading them in the terminal
On Linux and macOS (bash or zsh):
export LOG_LEVEL=debug # set and export to programs started afterward
echo "$LOG_LEVEL" # read the value
printenv LOG_LEVEL # another way to read it
env | sort # list all variables
LOG_LEVEL=info ./my-app # applies to this command only
unset LOG_LEVEL # remove the variable
In PowerShell (Windows, Linux, or macOS):
$env:LOG_LEVEL = "debug" # set it in the current session
$env:LOG_LEVEL # read the value
Get-ChildItem Env: # list all of them
Remove-Item Env:LOG_LEVEL # remove it
These commands only apply to the open terminal. If the terminal is still new to you, see how to use the terminal.
Reading them in code
In Python:
import os
port = int(os.environ.get("PORT", "8080")) # with a default value
log_level = os.environ.get("LOG_LEVEL", "info")
database_url = os.environ["DATABASE_URL"] # required: KeyError if missing
In Node.js:
const port = Number(process.env.PORT ?? 8080);
const logLevel = process.env.LOG_LEVEL ?? "info";
const databaseUrl = process.env.DATABASE_URL; // undefined if missing
Notice that environment variables are always text. Converting them to numbers or booleans is the application’s job.
.env files for local development
Exporting ten variables every time you open a terminal gets old. That’s why, in local development, it’s common to keep a .env file at the project root, read by libraries like python-dotenv or by the --env-file option in recent versions of Node.js:
# .env — for local development only
PORT=8080
LOG_LEVEL=debug
DATABASE_URL=postgres://app:local-password@localhost:5432/app
Two golden rules:
- The
.envfile never goes into Git. Add it to.gitignore. - Commit a
.env.examplewith the same names and fake values, so anyone joining the project knows what they need to configure.
# .gitignore
.env
.env.*
!.env.example
Configuration in Docker
With Docker, you pass variables when you start the container, without rebuilding the image:
docker run --rm -p 8080:8080 -e LOG_LEVEL=info your-org/app:1.0
docker run --rm -p 8080:8080 --env-file .env your-org/app:1.0
The same image runs in any environment; only the configuration changes. Avoid putting secrets in ENV in the Dockerfile: the value gets baked into the image, and anyone with access to it can read it.
Configuration in Kubernetes: ConfigMap and Secret
In Kubernetes, regular settings live in a ConfigMap and sensitive data in a Secret. The envFrom field turns every key in both into environment variables for the container:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
PORT: "8080"
LOG_LEVEL: "info"
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
spec:
replicas: 2
selector:
matchLabels:
app: app
template:
metadata:
labels:
app: app
spec:
containers:
- name: app
image: your-org/app:1.0
ports:
- containerPort: 8080
envFrom:
- configMapRef:
name: app-config
- secretRef:
name: app-secrets
The Secret shouldn’t go into Git in plain text. For testing, create it directly in the cluster, reading the value from a variable in your terminal:
kubectl create secret generic app-secrets --from-literal=DATABASE_URL="$DATABASE_URL"
Heads-up: the values in a Secret are only base64-encoded, not encrypted. Real protection depends on encryption at rest in etcd and on properly configured access control (RBAC).
An environment variable is not a vault
Environment variables are great for configuration, but they have limits when it comes to secrets: they show up in debug dumps, can leak into error logs, are inherited by child processes, and are visible through commands like docker inspect. For passwords, tokens, and keys, use a secrets manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, Google Secret Manager) and inject the value at runtime, for example with the External Secrets Operator in Kubernetes or by fetching the secret when the application starts. That gets you rotation, auditing, and access control. The article on silent DevSecOps shows how to stop secrets before they reach the repository.
The 12 factors, one per line
The 12-Factor App is a set of principles for applications that run as a service, created by Heroku engineers in the early 2010s. Environment variables are factor III, but it’s worth knowing all of them:
| # | Factor | In one sentence |
|---|---|---|
| I | Codebase | One repository per application, with many deploys from it |
| II | Dependencies | Declare every dependency explicitly, without relying on what’s “already installed” |
| III | Config | Everything that changes between environments lives outside the code, in the environment |
| IV | Backing services | Databases, queues, and caches are attached resources, swappable by changing configuration alone |
| V | Build, release, run | Keep building the artifact, combining it with configuration, and running it as separate stages |
| VI | Processes | The application runs as stateless processes; anything that must persist goes to a backing service |
| VII | Port binding | The application exposes its own service by listening on a port |
| VIII | Concurrency | Scale by running more processes, not bigger ones |
| IX | Disposability | Processes start fast and shut down gracefully when they receive a signal |
| X | Dev/prod parity | Keep development and production as similar as possible |
| XI | Logs | Write logs as a stream to standard output and let the environment collect them |
| XII | Admin processes | One-off tasks, like migrations, run with the same code and configuration as the application |
What matters most today (and the caveats)
Containers and Kubernetes made several factors almost automatic: dependencies ship in the image, port binding is the default, and logs on stdout are what collectors expect. The ones that still cause the most trouble in practice are III (config), VI (stateless processes), IX (disposability), and X (parity), topics covered in our guide to production-ready applications.
The caveats: the original text doesn’t cover secrets with the depth modern security demands, nor observability, and later books, such as Beyond the Twelve-Factor App, proposed extra factors like telemetry and security. Use the 12 factors as a starting point, not as law.
Validate configuration at startup (fail fast)
A missing variable shouldn’t be discovered at 3 a.m., when the first request tries to reach the database. Validate everything at startup and fail with a clear message:
import os
import sys
REQUIRED = ["DATABASE_URL", "PORT"]
missing = [name for name in REQUIRED if not os.environ.get(name)]
if missing:
sys.exit(f"Missing configuration: {', '.join(missing)}")
PORT = int(os.environ["PORT"])
In Kubernetes, a container that fails at startup shows up immediately as an error in the rollout, instead of serving broken responses. Libraries like pydantic-settings (Python), zod (TypeScript), and envconfig (Go) handle this validation with types.
Checklist
- No password, token, or production URL is written in the code
-
.envis in.gitignore, and a.env.exampleis committed - The same container image runs in every environment, with only the configuration changing
- In Kubernetes, regular settings are in a ConfigMap and secrets in a Secret, outside Git
- Critical secrets come from a secrets manager, injected at runtime
- The application validates required variables at startup and fails with a clear message
- Logs go to standard output, not to files inside the container
If changing environments means changing code, your configuration is in the wrong place.