如何在 Docker 构建中缓存 node_modules?

How to cache node_modules on Docker build?

一段时间以来,我一直在尝试在 Docker 构建中缓存 node_modules。我尝试了几种方法,包括 here,但没有成功。

我缓存的主要原因是构建图像需要 30+ 分钟,这太多了。

我的Dockerfile:

# This image will be based on the oficial nodejs docker image
FROM node:4.2.1

RUN npm install -g jspm@0.17.0-beta.7 && \
    npm install -g gulp && \
    npm install -g tsd

# Use changes to package.json to force Docker not to use the cache
# when we change our application's nodejs dependencies:
ADD package.json /src/package.json
RUN cd /src && npm install

# Put all our code inside that directory that lives in the container
ADD . /src

# Set in what directory commands will run
WORKDIR /src

# Install dependencies
RUN cd /src && \
    tsd reinstall -so && \
    jspm install && \
    gulp build -p

# Tell Docker we are going to use this port
EXPOSE 3000

# The command to run our app when the container is run
CMD ["npm", "run", "start-production"]

我没有 .dockerignore 文件。我之前添加了一个,但它仍然没有缓存我的 node_modules

那么,如何缓存我的 node_modules?随时提出对 Dockerfile.

的修改建议

谢谢!

我不确定它是否是错误的根源,但尝试在 ADD 命令中指定目标 文件夹而不是目标 file.

ADD package.json /src

此外,您可以使用 COPY 而不是 ADDADD 可以与 url 和存档,但你在这里不需要它)。

您还可以在文件的前面指定您的工作目录

尝试使用此代码:

    # This image will be based on the official nodejs docker image
    FROM node:4.2.1
    
    RUN npm install -g jspm@0.17.0-beta.7 && \
        npm install -g gulp && \
        npm install -g tsd

    # Set in what directory commands will run
    WORKDIR /src
    
    # Use changes to package.json to force Docker not to use the cache
    # when we change our application’s nodejs dependencies:
    COPY package.json ./

    RUN npm install
    
    # Put all our code inside that directory that lives in the container
    COPY . ./
    
    # Install dependencies
    RUN tsd reinstall -so && \
        jspm install && \
        gulp build -p
    
    # Tell Docker we are going to use this port
    EXPOSE 3000
    
    # The command to run our app when the container is run
    CMD ["npm", "run", "start-production"]