Is there a way to inject environment variables to all of my docker-compose services, without explicitly declaring them in each service's configuration?
CodePudding user response:
1)using the env_file directive
you can use the env_file
directive within your docker-compose.yml
file
You can pass multiple environment variables from an external file through to a service’s containers with the ‘env_file’ option, just like with
docker run --env-file=FILE ...
:
you will have to declare the env file for each service that will use it and that is it.
example :
the docker-compose.yml
file :
version: "3"
services:
database:
image: "ubuntu"
tty: true
env_file:
- same-variables.env
web:
image: "ubuntu"
tty: true
env_file:
- same-variables.env
the same-variables.env
file
IS_DOCKER_COMPOSE=yes
then if you do opening a terminal :
docker exec -it <docker_container> "echo $IS_DOCKER_COMPOSE"
result will be :
yes
2)using the .env file in project root
According to the doc: https://docs.docker.com/compose/environment-variables/#the-env-file
You can set default values for any environment variables referenced in the Compose file, or used to configure Compose, in an environment file named .env. The .env file path is as follows
Create an .env file as the root of your project as follow.
example :
your .env
file :
TAG=v1.5
your docker-compose.yml
file :
version: '3'
services:
web:
image: "webapp:$TAG"
organization of your project should be :
root_folder
|-.env
|-docker-compose.yaml
with the .env file with all your variable the env file will work for all of them at the same time