The Twelve-Factor App Approach
Configuration that varies between environments (development, staging, production) should be stored in environment variables, not in code.
.env Files
# .env
DATABASE_URL=mysql://user:pass@localhost/myapp
REDIS_URL=redis://localhost:6379
API_KEY=sk_live_abc123
DEBUG=false
LOG_LEVEL=warningLoading in Different Languages
# PHP
$dotenv = parse_ini_file('.env');
# Or use vlucas/phpdotenv package
# Node.js (with dotenv package)
require('dotenv').config();
console.log(process.env.DATABASE_URL);
# Python (with python-dotenv)
from dotenv import load_dotenv
load_dotenv()
import os
db_url = os.getenv('DATABASE_URL')Docker Compose
services:
app:
env_file:
- .env
# Or explicit:
environment:
- DATABASE_URL=${DATABASE_URL}Security Rules
- Never commit
.envto version control - Add
.envto.gitignore - Provide
.env.examplewith dummy values - Use separate files per environment:
.env.production,.env.staging - Restrict file permissions:
chmod 600 .env