2

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.

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

2 Comments

How can I use it with docker-compose? I'm using compose file.
@AshishGupta, please mark this as the accepted answer, since this is the best way to accomplish this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.