I have a docker-compose file which has a service that runs a postgres database image. The environment variables for the database (user, password, db_name) are in a env file called db.env
:
DB_USERNAME=some_user
DB_PASSWORD=thepassword
DB_NAME=database
As I want to have these variables only in one file I wanted to use this backand/db.env
file. The problem is, that the environemnt variable names differ from the ones which are used by postgres (DB_USERNAME <=> POSTGRES_USER).
This is the docker-compose.yml
file:
services:
db:
image: postgres
ports:
- 5432:5432
env_file:
- backend/db.env
environment:
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_USER=${DB_TEST}
- POSTGRES_DB=${DB_DATABASE}
I tried to use the same approach as when using the standard .env
file: Environment variables in Compose.
With a Command Line Argument The command used to launch Docker containers, docker run , accepts ENV variables as arguments. Simply run it with the -e flag, shorthand for --env , and pass in the key=value pair: sudo docker run -e POSTGRES_USER='postgres' -e POSTGRES_PASSWORD='password' ...
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.
Pass variables into Dockerfile through Docker Compose during build. If you want to pass variables through the docker-compose process into any of the Dockerfiles present within docker-compose. yml , use the --build-arg parameter for each argument to flow into all of the Dockerfiles.
But docker-compose does not stop at the . env and the host's current environment variables. It's cool that you can simply override values of your . env file, but this flexibility is can also be the source of nasty bugs.
env_file
will be available in the container .env
in compose file itself so you need to use .env
here
Workaround:
for i in $(cat < db.env); do export $i;done && docker-compose up -d
db.env:
DB_USERNAME=some_user
DB_PASSWORD=thepassword
DB_NAME=database
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