Ashish Gupta
Ashish Gupta

Reputation: 2614

How to get environment variable value from .env file in Dockerfile shell script?

How can I access environment variables defined in .env file in shell script?

.env file

USERNAME=user
PASSWORD=pass

Dockerfile

....

COPY ./compose/django/celery/worker/start_celery_flower.sh /start_celery_flower.sh
RUN sed -i 's/\r//' /start_celery_flower.sh
RUN chmod +x /start_celery_flower.sh

....

I tried using $USERNAME in shell script, but that is not working. I am able to access these variables in application running inside container.

Upvotes: 2

Views: 1239

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146630

docker build $(cat .env | xargs -n1 echo '--build-arg' | tr '\n' ' ') .

And in your Dockerfile add

ARG USERNAME
ARG PASSWORD

Basically you need to past build args using --build-arg. The command i posted will help in getting multiple ones from a file .

Edit-1

To use in docker-compose use like below

version: '3'
services:
  web:
    build:
      context: .
      args:
        - USERNAME=$USERNAME
        - PASSWORD=$PASSWORD

Now you need to export the variables before sending to docker-compose

set -a
source .env
set +a
docker-compose up --build -d

Upvotes: 2

Related Questions