You’ve set DATABASE_URL in your .env file. You’ve exported it in your shell. But your application still can’t find it. Sound familiar?
Environment variable issues are one of the most common — and frustrating — debugging sessions. Here’s a systematic guide to finding and fixing the problem.
The Quick Checklist
Before diving deep, check these common culprits:
- Did you restart your application? Environment variables are read at process start
- Are you in the right shell session? Variables exported in one terminal don’t exist in another
- Is your
.envfile in the right directory? Most libraries look in the current working directory - Did you spell it correctly?
DATABASE_URLvsDATABSE_URLhappens more than you’d think
Python: The os.environ Mystery
Problem: KeyError When Accessing Variables
| |
Fix 1: Check if the variable exists first
| |
Fix 2: Load your .env file properly
The os module doesn’t read .env files automatically. You need python-dotenv:
| |
Common mistake: Calling load_dotenv() after you’ve already tried to read the variable.
Problem: Variables Load Locally But Not in Production
Your .env file isn’t (and shouldn’t be) deployed to production. Check how your hosting platform handles environment variables:
| |
Node.js: Why process.env Is Empty
Problem: process.env.DATABASE_URL is undefined
| |
Fix: Use dotenv at the very start
| |
For ES modules:
| |
Common mistake: Importing other modules before dotenv:
| |
Docker: The Container Isolation Problem
Problem: Variables Set on Host Don’t Exist in Container
Containers are isolated. Your host’s environment variables don’t automatically transfer.
Fix 1: Pass variables explicitly
| |
Fix 2: Use Docker Compose
| |
Problem: Variables Work in docker run But Not in docker-compose
Check your .env file format:
| |
Also verify the file doesn’t have Windows line endings (CRLF). Convert with:
| |
Shell: Why export Didn’t Work
Problem: Variable Set in Script Doesn’t Persist
| |
| |
Scripts run in a subshell. Exports don’t affect the parent shell.
Fix: Source the script
| |
Problem: Variable Set But Application Can’t See It
Did you export it?
| |
Debugging Tips
Print all environment variables:
| |
| |
| |
Check where your app is looking:
| |
The Bottom Line
Environment variable issues almost always come down to:
- Timing — loading variables after you need them
- Scope — variables not reaching the right process
- Location — looking for
.envin the wrong directory - Format — typos, wrong syntax, or encoding issues
When in doubt, add debug logging to confirm what your application actually sees. The bug is usually simpler than you think.