Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass environment variable from external env file to container using docker compose

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.

like image 430
xooback Avatar asked Nov 27 '19 09:11

xooback


People also ask

How do I pass environment variables to docker containers?

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' ...

Can I use environment variables in Docker compose file?

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.

How do I pass an environment variable from Docker Compose to Dockerfile?

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.

Does Docker compose override environment variables?

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.


1 Answers

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
like image 59
LinPy Avatar answered Nov 15 '22 06:11

LinPy