为什么COPY package * .json ./在COPY之前..? [英] Why COPY package*.json ./ precedes COPY . .?

查看:83
本文介绍了为什么COPY package * .json ./在COPY之前..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此有关Docker的Node.js教程中: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

In this Node.js tutorial on Docker: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

COPY package * .json ./的意义是什么?

不是所有内容都用 COPY复制了..?

有问题的Dockerfile:

The Dockerfile in question:

FROM node:8

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm install --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "npm", "start" ]

推荐答案

这是Dockerfile(所有语言)中的常见模式. npm install 步骤花费很长时间,但是仅在软件包依赖项更改时才需要运行它.因此,通常看到第一步是安装依赖项,第二步是添加实际的应用程序,因为这使重建容器的过程变得更快.

This is a common pattern in Dockerfiles (in all languages). The npm install step takes a long time, but you only need to run it when the package dependencies change. So it's typical to see one step that just installs dependencies, and a second step that adds the actual application, because it makes rebuilding the container go faster.

您是对的,如果您一次构建映像,这本质上是相同的;您最终会得到相同的文件系统内容.

You're right that this is essentially identical if you're building the image once; you get the same filesystem contents out at the end.

尽管如此,但是在处理包装时会发生这种情况.您已更改了某些 src/*.js 文件,但尚未更改 package.json .您运行 npm test ,它看起来不错.现在,您重新运行 docker build .Docker注意到 package * .json 文件没有更改,因此它使用它初次构建的相同图像层,而无需重新运行任何内容,,并且它也跳过了npm install 步骤(因为它假定在相同的输入文件系统上运行相同的命令会产生相同的输出文件系统).因此,这使得 second 构建的运行速度更快.

Say this happens while you're working on the package, though. You've changed some src/*.js file, but haven't changed the package.json. You run npm test and it looks good. Now you re-run docker build. Docker notices that the package*.json files haven't changed, so it uses the same image layer it built the first time without re-running anything, and it also skips the npm install step (because it assumes running the same command on the same input filesystem produces the same output filesystem). So this makes the second build run faster.

这篇关于为什么COPY package * .json ./在COPY之前..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆