Using Environment Variables for Configuration
What you'll learn: How to read environment variables to configure your application differently in development, staging, and production—without changing code.
What Are Environment Variables?
Environment variables are key-value pairs set outside your application code, in the operating system or runtime environment. Think of them like sticky notes placed on your application's desk—they tell it "here's your database password for this environment" without writing that password into the code itself.
For example:
DATABASE_URLmight point tolocalhoston your laptop- The same
DATABASE_URLpoints to a production database URL on your server - Your code reads
DATABASE_URLthe same way in both places
Why Use Them?
Because configuration changes with the environment, but your code doesn't. You deploy the same codebase everywhere—only the environment variables change. This prevents:
- Hardcoding production secrets in code
- Maintaining multiple versions of configuration files
- Accidentally deploying dev settings to production
How to Read Environment Variables
Most languages provide simple access:
import os
db_url = os.environ.get('DATABASE_URL', 'default_value')
const dbUrl = process.env.DATABASE_URL || 'default_value';
Your application startup reads these values once, validates them (as you learned in Configuration Validation at Startup), and uses them throughout its lifecycle.
Common Pattern
Set environment variables before running your app:
export DATABASE_URL=postgres://localhost/mydb
export LOG_LEVEL=debug
python app.py
In production, your deployment platform (cloud provider, container orchestrator) injects the appropriate values automatically.
Key Takeaway: Environment variables let you configure application behavior per-environment without code changes, keeping secrets out of source control and enabling the same codebase to run everywhere.