Dockerfile: $HOME is not working with ADD/COPY instructions

Per the Docker docs, USER only applies to RUN, CMD and ENTRYPOINT.

The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.


Here's your problem:

When you use the USER directive, it affects the userid used to start new commands inside the container. So, for example, if you do this:

FROM ubuntu:utopic
RUN useradd -m aptly
USER aptly
RUN echo $HOME

You get this:

Step 4 : RUN echo $HOME
 ---> Running in a5111bedf057
/home/aptly

Because the RUN commands starts a new shell inside a container, which is modified by the preceding USER directive.

When you use the COPY directive, you are not starting a process inside the container, and Docker has no way of knowing what (if any) environment variables would be exposed by a shell.

Your best bet is to either set ENV HOME /home/aptly in your Dockerfile, which will work, or stage your files into a temporary location and then:

RUN cp /skeleton/myfile $HOME/myfile

Also, remember that when you COPY files in they will be owned by root; you will need to explicitly chown them to the appropriate user.