好的,所以我发现this great article 关于编写 docker 文件时的效率。
这是在运行RUN npm install 指令之前添加应用程序代码的错误 docker 文件示例:
FROM ubuntu
RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list
RUN apt-get update
RUN apt-get -y install python-software-properties git build-essential
RUN add-apt-repository -y ppa:chris-lea/node.js
RUN apt-get update
RUN apt-get -y install nodejs
WORKDIR /opt/app
COPY . /opt/app
RUN npm install
EXPOSE 3001
CMD ["node", "server.js"]
通过将应用程序的副本分成 2 个 COPY 指令(一个用于 package.json 文件,另一个用于其余文件)并在添加实际代码之前运行 npm install 指令,任何代码更改都不会触发运行 npm install 指令,只有 package.json 的变化才会触发它。更好的实践 docker 文件:
FROM ubuntu
MAINTAINER David Weinstein <david@bitjudo.com>
# install our dependencies and nodejs
RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list
RUN apt-get update
RUN apt-get -y install python-software-properties git build-essential
RUN add-apt-repository -y ppa:chris-lea/node.js
RUN apt-get update
RUN apt-get -y install nodejs
# use changes to package.json to force Docker not to use the cache
# when we change our application's nodejs dependencies:
COPY package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/
# From here we load our application's code in, therefore the previous docker
# "layer" thats been cached will be used if possible
WORKDIR /opt/app
COPY . /opt/app
EXPOSE 3000
CMD ["node", "server.js"]
这是添加 package.json 文件的地方,安装它的依赖项并将它们复制到应用程序所在的容器 WORKDIR 中:
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/
为避免每个 docker build 上的 npm install 阶段,只需复制这些行并将 ^/opt/app^ 更改为您的应用在容器内的位置。