我有一个看起来像这样的Dockerfile:
COPY ./aaa/package.json ./aaa/package.json
COPY ./bbb/package.json ./bbb/package.json
COPY ./ccc/package.json ./ccc/package.json
WORKDIR aaa
RUN npm install
COPY ./aaa ./aaa
基本上模块 aaa 使用 bbb 和 ccc 作为本地npm模块
是否可以编写它,以便用一条COPY指令完成前3个COPY指令,使它们成为1层而不是3层? (我意识到最后一个COPY包含第四层)
我仍然需要最后一次复制。那是故意的。拆分最后一层的原因是npm安装仅依赖于package.json文件,这样,如果我更改源代码,则不需要重建所有层,而只需重建最后一层。仅当我更改package.json文件时,才需要重建第一层并进行新的npm安装。对于我来说,使用单个模块是一种很好的模式,但是现在我有了一个使用本地子模块(本地npm模块)的主模块,我一直在坚持如何减少COPY指令的数量以减少层。 "Dockerizing a Node.js web app"
中的nodejs.org记录(推荐)了该技术的完整说明。值得一提的是,它在技术上可以按原样工作,但是它效率低下,因为当似乎有可能以某种方式将前三个COPY指令组合在一起以获得一层时,它会为多余的副本创建额外的层。
答案 0 :(得分:1)
You're trying to convert this to a many-to-many copy. This isn't supported by the Dockerfile syntax. You need to have a single destination directory on the right side. And if your source is one or more directories, you need to be aware that docker will copy the contents of those directories, not the directory name itself. The result is that you want:
COPY json-files/ ./
And then you need to organize your build context (in docker build .
the .
or current directory is your build context that is sent to the docker server to perform the build) with a directory called json-files
(could be any name) that contains only the files in the directory structure you want to copy:
| json-files/
|- aaa/package.json
|- bbb/package.json
\- ccc/package.json
Option 2:
You could structure your build as a multi-stage build to get this down to a single layer without modifying your build context itself:
FROM scratch as json-files
COPY ./aaa/package.json /json-files/aaa/package.json
COPY ./bbb/package.json /json-files/bbb/package.json
COPY ./ccc/package.json /json-files/ccc/package.json
FROM your_base
COPY --from=json-files /json-files .
WORKDIR aaa
RUN npm install
COPY ./aaa ./aaa
This second option is the same as the first from the the view of your COPY
command, it just has an image as it's context instead of the build context sent over with the build command.
All this said, changing from 3 copy commands to 1, for small individual files that do not overwrite each other, is unlikely to have any noticeable impact on your performance and this looks like premature optimization.