Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access env file variables in docker-compose file

I have an environment file that contain a variable called Database_User.

In my docker-compose, I have this:

services:
  database:
    container_name: postgres
    hostname: db
    image: postgres:12-alpine
    environment:
      - POSTGRES_USER=${Database_User}
   ports:
      - "54321:5432"
   env_file: project/myproject/.env

But, I am getting an error:

The Database_User variable is not set. Defaulting to a blank string.

like image 768
tempaccount as Avatar asked Feb 17 '26 12:02

tempaccount as


1 Answers

To get this right it is important to correctly understand the differences between the environment and env_file properties and the .env file:

  • environment and env_file let you specify environment variables to be set in the container:
    • with environment you can specify the variables explicitly in the docker-compose.yml
    • with env_file you implicitly import all variables from that file
    • mixing both on the same service is bad practice since it will easily lead to unexpected behavior
  • the .env file is loaded by docker-compose into the environment of docker-compose itself where it can be used
    • to alter the behavior of docker-compose with respective CLI environment variables
    • for variable substitution in the docker-compose.yml

So your current configuration does not do what you probably think it does:

env_file: project/myproject/.env

Will load that .env file into the environment of the container and not of docker-compose. Therefor Database_User won't be set for variable substitution:

environment:
  - POSTGRES_USER=${Database_User}

The solution here: remove env_file from your docker-compose.yml and place .env in the same directory you are starting docker-compose from. Alternatively you can specify an .env file by path with the --env-file flag:

docker-compose --env-file project/myproject/.env up
like image 142
acran Avatar answered Feb 20 '26 03:02

acran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!