Mirror318
Mirror318

Reputation: 12693

Does dotenv override envvars set by docker compose?

I'm not familiar with Docker or devops, but I have these files:

.env.production

DO_NOT_SEND_EMAILS=false

docker-compose.ci.yml

services:
  my-app:
    environment:
      - DO_NOT_SEND_EMAILS=true

Upvotes: 5

Views: 8818

Answers (3)

amit_saxena
amit_saxena

Reputation: 7624

As pointed out by DannyB dotenv doesn't override existing environment variables by default. For anyone using the dotenv CLI, you can override already existing environment variables using the --override or -o option like this:

dotenv -o -f ".env.local,.env"

Upvotes: 0

DannyB
DannyB

Reputation: 14796

It seems like dotenv does not override variables if they are defined in the environment, by design:

By default, it won't overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does. To overwrite existing environment variables you can use Dotenv.overload.

So the answer probably depends on how you are using dotenv - Dotenv.load or Dotenv.overload.

Here is a minimal test:

.env

SOMEVAR=from .env file
ANOTHERVAR=also from .env file

docker-compose.yml

version: '3'

services:
  test:
    build: .
    command: ruby test.rb
    volumes:
    - .:/app
    environment:
      SOMEVAR: from docker compose

Dockerfile

FROM dannyben/alpine-ruby
WORKDIR /app
RUN gem install dotenv
COPY . .

test.rb

require 'dotenv'

# values in .env will override
# Dotenv.overload

# values in .env will be used only if not already set in the environment
Dotenv.load

p ENV['SOMEVAR']
p ENV['ANOTHERVAR']

To run:

$ docker-compose build
$ docker-compose run test

Upvotes: 12

7urkm3n
7urkm3n

Reputation: 6321

As i know, it's not supposed to overwrite. Personally I use in docker env.

    env_file:
      - '.env.production'

instead of:

    environment:
      - DO_NOT_SEND_EMAILS=true

In this case always will rely on .env.prod file...

Upvotes: 2

Related Questions