Mr. Developerdude
Mr. Developerdude

Reputation: 9698

How to use environment variable from parent Docker file?

I have two Dockerfiles Dockerfile.A & Dockerfile.B where Dockerfile.B inherits using the FROM keyword from Dockerfile.A. In Dockerfile.A I set an environment variable that I would like to use in Dockerfile.B (PATH). Is this possible, and how would I go about doing it?


So far I have tried the following in Dockerfile.A:

  1. RUN export PATH=/my/new/dir:$PATH
    
  2. ENV PATH=/my/new/dir:$PATH
    
  3. RUN echo "PATH=/my/new/dir:$PATH" >/etc/profile
    

And in Dockerfile.B, respectively:

  1. Just use tools in the path to see if they were available (they were not)

  2. ENV PATH
    
  3. RUN source /etc/profile
    

I realized that every RUN command is executed in it's own environment, and that is probably why the ENV keyword exists, to make it possible to treat environments independently of the RUN commands. But I am not sure what that means for my case.

So how can I do this?

Upvotes: 1

Views: 4501

Answers (1)

johnharris85
johnharris85

Reputation: 18986

Works as expected for me.

Dockerfile.A

FROM alpine:3.6
ENV TEST=VALUE

Build it.

docker build -t imageA .

Dockerfile.B

FROM imageA
CMD echo $TEST

Build it.

$ docker build -t imageB .

Run it

$ docker run -it imageB
VALUE

Upvotes: 5

Related Questions