17

We've been using direnv for quite some time now to automatically load environment variables in a specific folder. And since version 3, docker-compose seems to support .env files.

The .envrc files used by direnv use export:

export NODE_ENV=development

Using the same file with docker-compose doesn't seem to work, only without export I get the value for the variable.

NODE_ENV=development

Any ideas on how to unify this into a single .env or .envrc file or an alternative to direnv?

eddies
  • 7,113
  • 3
  • 36
  • 39
Patrick
  • 7,903
  • 11
  • 52
  • 87

3 Answers3

19

Here is an alternative solution based on the comment chain for this answer

direnv ships with a stdlib that can be used to support classical 'dotenv' settings

# myproject/.envrc - name of current file

# Usage: 
# dotenv <optionalPathToDotEnvFile> or defaults to .env
dotenv
# myproject/.env
FOO=BAR

this is especially helpful when using container systems like docker that support the dotenv style

random-forest-cat
  • 33,652
  • 11
  • 120
  • 99
8

2022 update: direnv now supports .env files in addition to .envrc files.

Enable it like so:

$HOME/.config/direnv/direnv.toml

[global]
load_dotenv = true
Alec Rust
  • 10,532
  • 12
  • 48
  • 63
  • Thank you for this. The description for this option is here: https://direnv.net/man/direnv.toml.1.html#codeloaddotenvcode . I have proposed some changes here to make `load_dotenv` more clearer here:https://github.com/direnv/direnv/pull/1099 – Ativerc May 20 '23 at 15:38
7

I use the following setup to have variables available during dev from .envrc but using a docker-compose file for deployment:

In ./secrets define your variables as docker-compose needs them (without export):

foo=bar
secret_var=secret
...

In ./envrc export them to your shell:

#!bash
set -a
. ./secrets
set +a

set -a makes everything export by default, set +a turns this off afterwards.

wab
  • 797
  • 6
  • 19
  • 10
    Another way to do this is to use the `dotenv` function in the `.envrc`. That is part of the direnv stdlib. – zimbatm Jul 21 '18 at 12:38
  • There is not much documentation on this, so refer to the discussion here: https://github.com/direnv/direnv/issues/284#issuecomment-315275436 it's really as simple as having `dotenv` in the `.envrc` file. – Forethinker May 14 '19 at 01:43
  • the direnv stdlib can be found here https://direnv.net/man/direnv-stdlib.1.html – random-forest-cat Nov 14 '19 at 16:34