13

I have a Dockerfile that contains two WORKDIR statements (amid other ones) like so:

RUN pwd # reports /root
WORKDIR /tmp
RUN wget ...
RUN tar zxvf ...
RUN cd ... && ; ./configure && make && make install 
RUN sed ...
RUN sed ...
RUN rm ...
RUN rm -fr ...
WORKDIR $HOME
RUN pwd # reports /tmp (instead of /root)

I would expect pwd to be /root (i.e. $HOME for root) afterwards, but it remains at /tmp. Am I making an obvious mistake here? Is there a better way for restoring pwd to its "original" value.

Drux
  • 11,992
  • 13
  • 66
  • 116

1 Answers1

27

Seems like the best way would be to explicitly set your own default value so you can be sure it's consistent, like:

ENV HOME /root

WORKDIR $HOME
.. do something in /root ..

WORKDIR /tmp
.. do something else in /tmp ..

WORKDIR $HOME
.. continue back in /root ..

Note:

The WORKDIR instruction can resolve environment variables previously set using ENV. You can only use environment variables explicitly set in the Dockerfile.

https://docs.docker.com/engine/reference/builder/#/workdir

ldg
  • 9,112
  • 2
  • 29
  • 44
  • If you _are_ setting the value for $HOME in the Dockerfile, please post the rest of the file so we can see what's going on. – ldg Jul 17 '16 at 20:18
  • Added additional parts of the Dockerfile. – Drux Jul 17 '16 at 20:41
  • @Drux, I don't see a `ENV HOME ...` in your included Dockerfile. – BMitch Jul 17 '16 at 22:01
  • @BMitch I posted the version that does not use it. If I follow your suggestion, it would work. But I am still interested in why Dockerfile does not have access to `$HOME` without me having to set a specific value at its level. – Drux Jul 17 '16 at 22:03
  • 1
    Relying on external environment variables would mean each build of the same Dockerfile could result in a different image. That would be a bad thing for consistency. – BMitch Jul 17 '16 at 22:04
  • I see, so it's apparently [another instance](http://stackoverflow.com/questions/38426352/basic-docker-container-reports-runlevel-unknown) of the inside of a container is different from the inside of a VM image by design. Thx, so I assume @ldg's answer (with `ENV HOME /root`) is the way too go then. – Drux Jul 18 '16 at 01:23