'Docker build context puzzle
My project structure:
projectRoot/
- service/
- data.json
- Dockerfile
In that Dockerfile
:
FROM node:16.14-alpine3.14
ENV THE_DATA=/tmp/data.json
COPY data.json /tmp/data.json
Under project root, if I build the image:
docker build -t service:data_tmp -f service/Dockerfile .
I get error:
=> ERROR [2/2] COPY data.json /tmp/data.json
...
failed to compute cache key: "/data.json" not found: not found
I guess the error is due to the last .
indicates build context is project root, that's why the data.json
can't be located.
(My 2nd try) Then, I changed the Dockerfile
to:
FROM node:16.14-alpine3.14
ENV THE_DATA=/tmp/data.json
COPY ./service/data.json /tmp/data.json
But get error:
=> ERROR [2/2] COPY ./service/data.json /tmp/data.json
...
failed to compute cache key: "/service/data.json" not found: not found
(My 3rd try successful) I managed to make it eventually build successfully by changing the build context to /service/
:
docker build -t service:data_tmp -f service/Dockerfile /service/
But I don't get why my 2nd try above is not working? I mean in my 2nd try, even though build context is still .
meaning current directory, meaning project root, then, the path COPY
from ./service/data.json
should be correct. Why I still get error there?
Solution 1:[1]
When files that exist on the filesystem are not found in a COPY
step, check two things:
- Your context, which was done here. That's the
.
at the end of the build command saying the context is the current directory. If you pass a different directory, that is the source forCOPY
steps (at least those that don't change the source with a--from
). - A
.dockerignore
file. This is in the root of the context, and has a syntax similar to.gitignore
. When changing the context, you change the location docker checks for the.dockerignore
file.
A common pattern for a minimal docker build is to specify the .dockerignore
file with:
*
!src
# ...
Which tells docker to exclude everything on the first line, and then reinclude src
on the second line. You would add additional lines to reinclude the folder here with !service
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BMitch |