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

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

问题描述

在这篇关于 Docker 的 Node.js 教程中:https://nodejs.org/en/docs/guides/nodejs-docker-网络应用程序/

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" ]

推荐答案

这是 Dockerfiles(所有语言)中的常见模式.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 step(因为它假设在相同的输入文件系统上运行相同的命令会产生相同的输出文件系统).所以这使得第二次构建运行得更快.

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天全站免登陆