简体   繁体   中英

How to cache node_modules for unchanged package.json during yarn / npm install during docker build?

I have a Dockerfile for a node application looking like this:

FROM node:8.3
ENV TERM=xterm-color NPM_CONFIG_LOGLEVEL=warn PATH="$PATH:/usr/src/app/node_modules/.bin/"
WORKDIR /usr/src/app
ADD . /usr/src/app
RUN yarn install --frozen-lockfile --ignore-platform --ignore-engines --quiet && tsc && webpack
CMD ["node", "/usr/src/app/server"]

Yet this means that on every change to the sourcetree, the layer with RUN yarn install ... will be invalidated and run again.

As yarn install by itself takes about 80s, the built is unnecessarily slowed down even if only a Readme.md changed.

I want to use only run yarn install once either the package.json or yarn.lock changes.

This question would also apply to npm and its packlage

You can cache the package.json and the appropriate lock file and run the intallation in a temp folder. After adding the source, you can mv the node_modules and files into the main app folder.

Here's an example if using yarn install .

FROM node:8.3
ENV TERM=xterm-color NPM_CONFIG_LOGLEVEL=warn PATH="$PATH:/usr/src/app/node_modules/.bin/"
VOLUME ["/logs"]
WORKDIR /tmp/node
ADD package.json yarn.lock ./
RUN yarn install --frozen-lockfile --ignore-platform --ignore-engines --quiet
WORKDIR /usr/src/app
ADD . /usr/src/app
RUN mv /tmp/node/* ./ && tsc && webpack
CMD ["node", "/usr/src/app/server"]

A quick metric using time return these output for the tweaked Dockerfile on docker build . :

  • On source file change:
    • 0m34.084s
  • On yarn.lock change:
    • 2m22.774s

For npm, you would need, depending on your version, need to add either

  • npm-shrinkwrap.json
  • package-lock.json

as insted of the yarn.lock file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM