Home > Software design >  How to pass .env variables from docker-compose to entrypoint's script?
How to pass .env variables from docker-compose to entrypoint's script?

Time:11-25

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}"

CodePudding user response:

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
  • Related