1. Home
  2. Blog
  3. DevOps

DevOps

Environment Variables Explained: .env Files, Secrets and Config Done Right

Environment variables let the same code run on a laptop, in CI and in production with different settings. Here is how they really behave, with the surprises we hit while testing them.

8 min read
Environment variables explained: .env files, secrets and config done right

Key takeaways

  • 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 .env files 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 .env out 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:

  1. 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.
  2. Was the app restarted? A running process keeps the environment it started with. Changing a variable afterwards has no effect until the restart.
  3. Is the name exact? Names are case-sensitive on Linux and macOS, so App_Port and APP_PORT are different variables. Windows treats them as the same.
  4. Is a .env file overriding it, or being ignored? Check whether your loader overrides existing values, and which file it actually reads.
  5. 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →