Copy file into Dockerfile from different directory

3/24/2020

Is it possible for Dockerfile to copy over some file from the host filesystem and not from the context it's being build from ?

# Inside Dockerfile
FROM gradle:latest
COPY ~/.super/secrets.yaml /opt

# I think you can work around it with but doesn't look nice
COPY ../../../../../../.super/secrets.yaml /opt

when I ran the command on the /home/user/some/path/to/project/ path ?

docker build .
-- potatopotato
docker
kubernetes

3 Answers

3/24/2020

The usual way to get "external" files into your docker container is by copying them into your build directory before starting the docker build. It is strongly recommended to create a script for this to ensure that your preparation step is reproducible.

-- Manziel
Source: StackOverflow

3/24/2020

No this is not possible to go up the directory. Here is why.

When runnig docker build . have you ever considered what this dot stand for at the end? Well, here is part of docker documentation

The docker build command builds Docker images from a Dockerfile and a “context”. A build’s context is the set of files located in the specified PATH or URL. The build process can refer to any of the files in the context. For example, your build can use a COPY instruction to reference a file in the context.

As you see, this dot is referencing context path (here it means "this directory"). All files under context path get sent to docker daemon and you can reference only these files in your Dockerfile. Of course, you can think that you are clever and reference / (root path) so you have access to all files on your machine. (I highly encourage you to try this and see what happens). What you should see that happens is that docker client is freezing. Or, does it really? Well, it's not really freezing, its sending all / directory to docker daemon and it can take ages or (what's more probable) you may run out of memory.

So now when you understand this limitation you see that the only way to make it work is to copy the file you are interested in to the location of context path and then run docker build command.

-- HelloWorld
Source: StackOverflow

3/24/2020

When you do docker build ., that last argument is the build context directory: you can only access files from it.

You could do docker build ../../../ but then every single file in that root directory will get packaged up and send to the Docker daemon, which will be slow.

So instead, do something like:

cp ../../../secret.yaml .
docker build .
rm secret.yaml

However, keep in mind that will result in the secret being embedded in the image forever, which might be a security risk. If it's a secret you need for runtime, better to pass it in via environment variable at runtime. If you only need the secret for building the image, there are other alternatives, e.g. https://pythonspeed.com/articles/docker-build-secrets/.

-- Itamar Turner-Trauring
Source: StackOverflow