Why is the COPY instruction causing a cache miss in my Docker build

試著忘記壹切 提交于 2020-02-21 07:04:32

问题


The copy instruction in the docker file for my project seems to cause a cache miss, even though none of the files being copied have changed since the image was last pushed to docker hub. This causes all subsequent layers to miss the cache which makes the build take much longer than it should. I've also noticed that the hashes belonging to each layer seem to be different than what they are when I docker build on my local machine. Could this be because of a docker version mismatch? What is going on here? How can I diagnose this?


回答1:


Check the layers of the different images being built with docker history --no-trunc $image. On the copy step, you'll see a "file:abc" hash of the files being copied:

IMAGE                                                                     CREATED             CREATED BY                                                                                                        SIZE                COMMENT
sha256:202cb043f70a2565ea40629e891642e1e24be7b52e29116a6520736f47183904   9 minutes ago       /bin/sh -c #(nop) COPY file:d523f0d1cac93e44179baf9c36a7a4feff221b604224e26900075ddb02812448 in /test/test.txt    12B

If that hash is different between the two images you are building, then that will invalidate the build cache and result in the miss. Keep in mind the metadata of the files can also cause a cache miss, especially the file permissions. If you're still having problems, then please update the question to include the docker history --no-trunc ... output from the different builds.




回答2:


If the contents of your file have indeed not changed, differences in permissions can cause cache invalidation.

For the ADD and COPY instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated.

https://docs.docker.com/develop/develop-images/#leverage-build-cache




回答3:


How are you completely sure any file was modified in the context?
Do you have a .dockerignore file with all the files/directories you want to ignore in the moment docker sends the context to the engine?

There are a lot of files than can be getting modified and you don't know. For example, if you have a .git folder in the mentioned context and you made a git commit, now your cache will be invalidated.

Be sure you ignore the unneeded files in the .dockerignore file.



来源:https://stackoverflow.com/questions/49932954/why-is-the-copy-instruction-causing-a-cache-miss-in-my-docker-build

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!