2

I am new to docker. I would like to understand the following questions. I have been searching but I can't find the answers to my questions.

  1. Why do I always get a wrong path when I tried to copy the file?

  2. Does that mean I can only copy the files into the docker image from the same directory where I have my dockerfile? Is there a way to COPY files from other directories on the host?

  3. Is there a way to passing in host's environment variables directly in the Dockerfile without using "ARG" and --build-arg flag?

Below is what I currently have

file structure is like this:

/home/user1/docker 
|__ Dockerfile

In the Dockerfile:

From 

ARG BLD_DIR=/tmp

RUN mkdir /workdir

WORKDIR /workdir

COPY ${BLD_DIR}/a.file /workdir

I ran

root@localhost> echo $BLD_DIR
/tmp/build <-- BLD_DIR is a custom variable; meaning it's different on each dev env

docker build --build-arg BLD_DIR=${BLD_DIR} -t docker-test:1.0 -f Dockerfile 

Always got error like

COPY failed: stat /var/lib/docker/tmp/docker-builder035089075/tmp/build/a.file: no such file or directory

asun
  • 151
  • 5
  • 15

1 Answers1

3
  1. In a Dockerfile, you can only copy files that are available in the current Docker build context.

By default, all files in the directory where you run your docker build command are copied to the Docker context folder.

So, when you use ADD or COPY commands, all your paths are in fact relative to build folder, as the documentation states:

Multiple resources may be specified but the paths of files and directories will be interpreted as relative to the source of the context of the build.

This is voluntary because building an image using docker build should not depend on auxiliary files on your system: the same Docker image should not be different if built on 2 different machines.

  1. However, you can have a directory structure like such:

    /home/user1/
    |___file1
    |___docker/
    |___|___ Dockerfile
    

If you run docker build -t test -f docker/Dockerfile . in the /home/user1 folder, your build context will be /home/user1, so you can COPY file1 in your Dockerfile.

  1. For the very same reason, you cannot use environment variables directly in a Dockerfile. The idea is that your docker build command should "pack" all the information needed to generate the same image on 2 different systems. However, you can hack your way around it using docker-compose, like explaned here: Pass host environment variables to dockerfile.
sachav
  • 1,316
  • 8
  • 11