Using direnv to Manage Environment Variables for Multi‑Environment Docker Projects
This article introduces the direnv tool and demonstrates how to isolate and automatically load environment variables for different Docker‑based development, testing, and staging setups, reducing manual exports and streamlining multi‑environment workflows on a single machine.
Many developers who work with Linux are familiar with environment variables, but repeatedly exporting them for different projects can be cumbersome and error‑prone. This guide presents direnv, a lightweight utility that automatically loads per‑directory environment settings, simplifying the management of dev, test, and stage environments.
The example scenario involves running code inside Docker containers, using Docker Compose to orchestrate multiple services, and storing environment variables in separate .env files. Different Compose files (e.g., docker-compose-dev.yml, docker-compose-test.yml, docker-compose-stage.yml) are used for each environment, and a CODE_DIR variable must be exported before invoking Docker commands.
To avoid manual exports, the author created a start.sh script (shown in the original images) that launches the appropriate Compose file. However, the desired workflow is to automatically set the required variables simply by changing directories.
Installing direnv # aptitude install direnv After installation, add the direnv hook to the shell initialization file ( ~/.bashrc or ~/.zshrc). eval "$(direnv hook bash)" In each project directory, create a .envrc file containing the needed exports, for example:
export COMPOSE_HTTP_TIMEOUT=200
export CODE_DIR=/home/xiaomi/running/code_stage
export RUN_ENV=stageAllow direnv to load the file:
cd ~/running/code_stage
direnv allow .When you cd into the directory, direnv automatically applies the variables defined in .envrc and displays a status message. You can also check the currently loaded variables with direnv status.
Tips
After modifying .envrc, run direnv allow again to reload the changes.
Because direnv executes .envrc on directory entry, you can embed additional commands (e.g., launching a script) to further automate workflows.
The article invites readers to explore other use cases for direnv in their development and operations processes.
NetEase Game Operations Platform
The NetEase Game Automated Operations Platform delivers stable services for thousands of NetEase titles, focusing on efficient ops workflows, intelligent monitoring, and virtualization.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
