xooback
xooback

Reputation: 593

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.

Upvotes: 6

Views: 3842

Answers (2)

Adiii
Adiii

Reputation: 59966

Why you define Environment variable again once you defined in db.env? You can utilize the same db.env. Just set Environment variables name in db.env according to Postgres environment variable name, you can fine here .

db.env

POSTGRES_PASSWORD=pass
POSTGRES_USER=user
POSTGRES_DB=db

and docker compose

services:
  db:
    image: postgres
    ports:
      - 3306:3306
    env_file: 
      - db.env

docker-compose up and then try to verify DB and user

docker exec -it <container_id> bash -c "psql -U user -l"

output

docker-user$  docker exec -it postgress-env_db_1 bash -c "psql -U user -l"
                             List of databases
   Name    | Owner | Encoding |  Collate   |   Ctype    | Access privileges 
-----------+-------+----------+------------+------------+-------------------
 db        | user  | UTF8     | en_US.utf8 | en_US.utf8 | 
 postgres  | user  | UTF8     | en_US.utf8 | en_US.utf8 | 
 template0 | user  | UTF8     | en_US.utf8 | en_US.utf8 | =c/user          +
           |       |          |            |            | user=CTc/user
 template1 | user  | UTF8     | en_US.utf8 | en_US.utf8 | =c/user          +
           |       |          |            |            | user=CTc/user
(4 rows)

Or if you want the same env then you can pass like

(export $(cat db.env | xargs) && docker-compose up )

Upvotes: 1

LinPy
LinPy

Reputation: 18578

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

Upvotes: 4

Related Questions