Is it possible to specify the env file that docker compose uses for variable substitution? Currently it defaults to ".env" but I have different flavours of compose files which should have different envs.
You can set default values for environment variables using a .env file, which Compose automatically looks for in project directory (parent folder of your Compose file). Values set in the shell environment override those set in the .env file. Note when using docker stack deploy.
Docker Compose allows us to pass environment variables in via command line or to define them in our shell. However, it's best to keep these values inside the actual Compose file and out of the command line.
ENV is mainly meant to provide default values for your future environment variables. Running dockerized applications can access environment variables. It's a great way to pass configuration values to your project. ARG values are not available after the image is built.
env. example file documents the application's necessary variables and can be committed to version control. This serves as a helpful reference and speeds up the onboarding process for new team members by reducing the amount of time spent digging through the coding to figure out what needs to be set up.
You can use inheritance for this. If you have one "base" service where you set up the environment, all of your other services can inherit from that.
Example:
version: "2"
services:
base:
env_file:
- my_env.txt
web:
extends:
service: base
image: foo
database:
extends:
service: base
image: foo-db
The above example has everything in the same file, but you can also split this up into multiple files, where the base
service would reside in a base.yaml
file. You just need to add file: base.yaml
to the extends
section. Please see the documentation here.
I use this approach for setting the proxy variables for all containers. I have a proxy.yaml
file that defines a proxy-app
service that picks up the proxy environment variables from the shell. All of my real services extend the proxy-app
service and thus inherit the environment settings from that service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With