1

How can I make the bash script to see env variables set on .env and/or inside docker-compose yaml?

.env

VARIABLE_ENV=VALUE_ENV

docker-compose.yml

version: '3'

services:
  service:
    volumes:
      - ./entrypoint.sh:/entrypoint.sh
    environment:
      - VARIABLE_YML=VALUE_YML
    entrypoint: /entrypoint.sh

entrypoint.sh

#!/bin/bash

echo -e "${VARIABLE_ENV}"
echo -e "${VARIABLE_YML}"
Bruno Massa
  • 55
  • 1
  • 1
  • 10
  • Once you mount in the .env file, by adding a volume, then you can [source it in](https://stackoverflow.com/questions/43267413/shell-how-to-set-environment-variables-from-env-file) ... or load it into the compose with env_file – Lawrence Cherone Nov 24 '21 at 17:27

1 Answers1

4

The .env file sets variables that are visible to Compose, in the same way as if you had exported them in your containing shell, but it doesn't automatically set those in containers. You can either tell Compose to pass through specific variables:

environment:
  - VARIABLE_YML=VALUE_YML # explicitly set
  - VARIABLE_ENV           # from host environment or .env file

Or to pass through everything that is set in the .env file:

environment:
  - VARIABLE_YML=VALUE_YML # as above
env_file: .env

The other important difference between these two forms is whether host environment variables or the .env file takes precedence. If you pass through a value in environment: then the host environment variable wins, but if it's in env_file:, .env is always used.

VARIABLE_ENV=foo docker-compose up
David Maze
  • 130,717
  • 29
  • 175
  • 215
  • Thanks David. `env_file: .env` worked. In fact, I must confess that I did not tested reading the values set in the YAML file, just the one inside the .env file. I assumed they worked the same way, but in fact, the ones set in the YAML are visbile to the script, while the .env have to be told to. – Bruno Massa Nov 24 '21 at 17:33
  • 1
    This isn't clear in the docker docs. Your answer should be incorporated into them for those trying to overwrite shell env vars with those in an `.env` file. Thanks! – j7skov Mar 03 '22 at 17:34