- Environment variables are key-value settings that a process receives from its environment.
- They keep config, like ports and database URLs, out of your code.
- Values are always strings, so “false” is truthy unless you parse it.
- Never commit
.envfiles with real secrets, and validate required settings when the app starts.
Your app needs a database URL. On your laptop it is a local database, in CI a throwaway one, and in production a managed cluster. Hard-coding any of them means changing code for each environment. Environment variables solve this. The code reads DATABASE_URL, and each environment supplies its own value.
This idea is central to the Twelve-Factor App method, which says config that varies between deployments belongs in the environment. We tested the behaviour below with Python 3.13 on Windows. Every output shown is from that run.
What are environment variables?
Every running process has a set of named text values called its environment. Familiar examples are PATH, which tells the shell where to find programs, and HOME or USERPROFILE. Your own app can use the same mechanism for settings like APP_PORT, LOG_LEVEL or DATABASE_URL.
Setting environment variables
| Shell | For this session | For one command |
|---|---|---|
| Bash / zsh | export APP_PORT=8080 |
APP_PORT=8080 python app.py |
| PowerShell | $env:APP_PORT = "8080" |
Set it, run, then remove it |
| Windows cmd | set APP_PORT=8080 |
Not built in |
These last only for the current terminal session. To make them permanent, add them to a shell profile such as ~/.bashrc, or, on Windows, use the system environment settings or setx. For applications, it is usually better to supply them at deploy time rather than setting them system-wide.
Reading them in code
import os
port = os.environ.get("APP_PORT", "8000") # default if missing
print(port) # 8000
db = os.environ["DATABASE_URL_MISSING_DEMO"]
# KeyError: 'DATABASE_URL_MISSING_DEMO'
Use .get() with a default for optional settings. Use square brackets, which raise KeyError, for settings the app cannot work without. Other languages are similar: process.env.APP_PORT in Node.js, System.getenv("APP_PORT") in Java and os.Getenv("APP_PORT") in Go.
Everything is a string
This catches people in every language. We set a port and then added “1” to it:
os.environ["APP_PORT"] = "8080"
port = os.environ["APP_PORT"]
print(type(port).__name__, repr(port), port + "1")
# str '8080' 80801
os.environ["APP_PORT"] = 8080
# TypeError: str expected, not int
The value came back as text, and adding produced 80801, not 8081. Convert explicitly, as in int(os.environ["APP_PORT"]). Booleans are worse:
os.environ["DEBUG"] = "false"
print(bool(os.environ["DEBUG"])) # True
Any non-empty string is truthy in Python, so "false" became True. Debug mode would have been switched on in production. Parse booleans deliberately:
def env_bool(name, default=False):
value = os.environ.get(name)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
env_bool("DEBUG") # False
env_bool("NOT_SET", default=True) # True
How processes inherit them
A child process receives a copy of its parent’s environment. We started child Python processes to see this:
child sees: 8080 inherited # default: full copy of the parent's environment
child sees: 9000 None # given a custom env: only what we passed
parent sees child var: None # a child's changes never flow back
Three practical lessons follow. Variables you export are visible to every program you launch, including scripts you did not write, which matters for secrets. Passing a custom environment replaces the whole thing, so include anything the child needs. And a script cannot change its parent shell’s variables, which is why tools ask you to source a file instead of running it.
.env files
Typing many variables by hand gets tedious, so most projects keep local development values in a .env file:
# local development only
APP_PORT=8080
DATABASE_URL="postgres://dev:devonly@localhost:5432/shop"
FEATURE_SEARCH=true
Libraries such as python-dotenv, and dotenv for Node.js, load this file at startup. Node.js 20.6 and later can also load one natively with --env-file. To see the idea, we wrote a tiny parser, which turned the file above into:
{'APP_PORT': '8080',
'DATABASE_URL': 'postgres://dev:devonly@localhost:5432/shop',
'FEATURE_SEARCH': 'true'}
Use a real library in practice. It handles quoting, escapes, comments and multi-line values that our 10-line version ignores. By default, most dotenv loaders do not override variables that are already set, so real environment values win over the file. That is usually what you want.
Tip: Add .env to .gitignore before your first commit, and commit a .env.example with every variable name and safe placeholder values instead. New developers copy it and fill in their own values.
Validate configuration at startup
A missing variable should stop the app immediately with a clear message, not cause a confusing error an hour later. We checked for required settings when loading:
REQUIRED = ["DATABASE_URL", "SECRET_KEY"]
def check_required(env):
missing = [k for k in REQUIRED if not env.get(k)]
if missing:
raise SystemExit(f"Missing required settings: {', '.join(missing)}")
# Missing required settings: SECRET_KEY
Typed config libraries go further. Pydantic Settings in Python, zod or envalid in Node.js, and Spring’s configuration properties in Java all convert types and report every problem at once.
Environment variables and secrets
Environment variables are the common way to pass secrets like API keys to an app, and they are far better than hard-coding them. They do have weaknesses to know about:
- Child processes inherit them, as our test showed.
- They can appear in crash reports, debug pages and logs that dump the environment.
- On some systems, other processes run by the same user can read them.
For production, many teams keep secrets in a dedicated manager, such as HashiCorp Vault, AWS Secrets Manager, Azure Key Vault or Google Secret Manager, and inject them at runtime. Some prefer mounting secrets as files instead of variables. Either way, never print config in logs, and rotate any secret that was ever committed to Git, even after you remove it from history.
In Docker and CI
# Docker (not run for this article)
docker run -e APP_PORT=8080 --env-file .env.production myapp
# GitHub Actions (not run for this article)
env:
APP_PORT: 8080
API_KEY: ${{ secrets.API_KEY }}
CI platforms store secrets encrypted and mask them in logs. Avoid baking secrets into Docker images with ENV in the Dockerfile, because they remain readable in the image layers. See our Docker Compose tutorial and GitHub Actions CI/CD guide for complete setups.
Best practices
- Use clear, uppercase names with a prefix, such as
SHOP_DB_URL. - Read all config in one module, convert types there, and validate at startup.
- Provide safe defaults only for non-sensitive settings.
- Keep
.envout of Git and maintain a.env.example. - Use a secrets manager in production for sensitive values.
- Document every variable, its type and an example value.
Debugging environment variable problems
When an app behaves as if a setting is missing, work through these checks in order:
- Is it set in the right place? A variable exported in one terminal tab does not exist in another, or in a service started by the system.
- Was the app restarted? A running process keeps the environment it started with. Changing a variable afterwards has no effect until the restart.
- Is the name exact? Names are case-sensitive on Linux and macOS, so
App_PortandAPP_PORTare different variables. Windows treats them as the same. - Is a .env file overriding it, or being ignored? Check whether your loader overrides existing values, and which file it actually reads.
- Are there stray quotes or spaces? A value copied with a trailing space or extra quotes can fail to parse, or fail to match, in ways that are hard to spot.
To see what a process really received, print the variable names, never the values of secrets. On Linux and macOS, printenv lists the current shell’s environment, and in PowerShell Get-ChildItem Env: does the same. Inside a container, running env through docker exec shows the container’s view, which is often different from your own shell’s.
A last tip: log one line at startup that lists which optional settings are using their defaults. It costs nothing, and it answers most “why is it doing that?” questions straight away.
Final thoughts
Environment variables are simple, but they hide a few traps: everything is a string, children inherit them, and secrets can leak through them. Treat them as an input to your app. Read them in one place, convert and validate them early, and keep real secrets out of files that get committed.
Frequently asked questions
What is an environment variable?
It is a named text value that a process receives from its environment, such as APP_PORT=8080. Apps use them for settings that change between environments.
What is a .env file?
A text file of KEY=value lines, loaded at startup by a library such as python-dotenv. It is used mainly for local development and should not be committed with real secrets.
Why is my environment variable a string?
Operating systems store environment values as text. Convert numbers with int() and parse booleans explicitly, because the string “false” counts as true.
Are environment variables secure for secrets?
They are better than hard-coding, but child processes inherit them and logs can expose them. Production systems often use a dedicated secrets manager.
Can a script change its parent shell’s variables?
No. A child process gets a copy of the environment, so its changes do not flow back. To set variables in the current shell, source the file instead.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.