Dockerfile COPY cannot find the file

Stanley Meng
1 min readFeb 6, 2022

--

You might get this error when COPY a file from host to the container.

COPY failed: file not found in build context or excluded by .dockerignore: stat <Filename>: file does not exist

Well… most of the online posts suggested to check .dockerignore file.

I was lilke…Okey. Maybe, checking the .dockerignore file is the first step you should go.

The error message has given a great hint, the file is not in the build context!!!

For instance,

You create a path ~/test/docker/

Put the Dockerfile in ~/test/docker/Dockerfile, which looks like this :

FROM Ubuntu
COPY ~/.ssh/known_host /root/known_host

Then, run the docker build in ~/test/docker/, you’ll see the error above. Because the build context in this case is within ‘~/test/docker/’ , the docker build command is unable to visit any file out of this path, it only is aware of the files in ~/test/docker/* .

Therefore, either you copy the ~/.ssh/known_host to ~/test/docker/ or its sub-dir, or you have to switch your build context to ~ in this case.

But it might introduce another issue — the docker build will send the context to the docker daemon before it starts the build, that will take a long time ifyour home dir is very huge,.

OK, you can use .dockerignore file now, but I prefer another solution: https://docs.docker.com/develop/develop-images/build_enhancements/

Very straightforward, just add ‘DOCKER_BUILDKIT=1' prior to your ‘docker build’ command. E.g.

DOCKER_BUILDKIT=1  docker build  -t test123  .

it runs like a flash…

--

--

No responses yet