Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables in docker-compose are substituted as empty string

Though having read the Docker documentation about environment variables I have some trouble understanding the variable substitution.

This is my current docker-compose.yml:

version: '3'
services:
  web:
    image: myimage:latest
    environment:
      FRONTEND_URL: http://mydomain
      CALLBACK_URL: ${FRONTEND_URL}/callback

My understanding so far is that I can use something like ${FRONTEND_URL} so that CALLBACK_URL will be interpolated to http://mydomain/callback, but after a docker-compose up this service has the following environment values:

FRONTEND_URL: http://mydomain
CALLBACK_URL: /callback

So it looks as if ${FRONTEND_URL} is not substituted. What am I missing here?

like image 735
Robert Strauch Avatar asked Nov 21 '25 15:11

Robert Strauch


1 Answers

You can use a .env file on the same folder a docker-compose.yml.

.env

FRONTEND_URL=http://mydomain

docker-compose.yml

version: '3'
services:
  web:
    image: myimage:latest
    environment:
      FRONTEND_URL: ${FRONTEND_URL}
      CALLBACK_URL: ${FRONTEND_URL}/callback

enter image description here


Instead of using the .env file you can use export. Run this command before docker-compose up:

export FRONTEND_URL=http://mydomain

Now you can use this docker-compose.yml:

version: '3'
services:
  web:
    image: myimage:latest
    environment:
      FRONTEND_URL: ${FRONTEND_URL}
      CALLBACK_URL: ${FRONTEND_URL}/callback

If an environment variable is not set, Compose substitutes with an empty string. In the example above, if POSTGRES_VERSION is not set, the value for the image option is postgres:.

You can set default values for environment variables using a .env file, which Compose automatically looks for. Values set in the shell environment override those set in the .env file.

source: https://docs.docker.com/compose/compose-file/#variable-substitution

like image 91
Sebastian Brosch Avatar answered Nov 23 '25 06:11

Sebastian Brosch



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!