Docker实践(25) – 不使用缓存重建镜像

使用Dockerfile构建镜像可以利用它的缓存功能:只有在命令已更改的情况下,才会重建已构建的步骤。下面是重新构建之前涉及到的to-do app的示例:

  1. $ docker build .
  2. Sending build context to Docker daemon  2.56 kB
  3. Sending build context to Docker daemon
  4. Step 0 : FROM node
  5.   —> 91cbcf796c2c
  6. Step 1 : MAINTAINER [email protected]
  7.  —> Using cache
  8. Indicates you’re using the cache
  9. Specifies the cached image/layer ID
  10.    —> 8f5a8a3d9240
  11. Step 2 : RUN git clone -q https://github.com/docker-in-practice/todo.git
  12.  —> Using cache
  13.  —> 48db97331aa2
  14. Step 3 : WORKDIR todo
  15.  —> Using cache
  16.  —> c5c85db751d6
  17. Step 4 : RUN npm install > /dev/null
  18.  —> Using cache
  19.  —> be943c45c55b
  20. Step 5 : EXPOSE 8000
  21.  —> Using cache
  22.  —> 805b18d28a65
  23. Step 6 : CMD npm start
  24.  —> Using cache
  25.  —> 19525d4ec794
  26. Successfully built 19525d4ec794

缓存非常有用并且省时间,不过有时候docker缓存的行为不都能达到你的期望。
用以上Dockerfile作为示例,假设你更改了代码并push到Git仓库。新代码不会check out下来,因为git clone命令没有更改。在Docker看来git clone的步骤一样,所以使用了缓存。
在这种情况下,你可能不想开启docker的缓存了。

问题

你想不用缓存重建Dockerfile。

解决方法

构建镜像时使用–no-cache参数。

讨论

为了强制docker构建镜像时不用缓存,执行带–no-cache参数的docker build命令。下面的示例是使用了–no-cache构建镜像。

  1. $ docker build –no-cache .
  2. Sending build context to Docker daemon  2.56 kB
  3. Sending build context to Docker daemon
  4. Step 0 : FROM node
  5.  —> 91cbcf796c2c
  6. Step 1 : MAINTAINER [email protected]
  7.  —> Running in ca243b77f6a1
  8.  —> 602f1294d7f1
  9. Removing intermediate container ca243b77f6a1
  10. Step 2 : RUN git clone -q https://github.com/docker-in-practice/todo.git
  11.  —> Running in f2c0ac021247
  12.  —> 04ee24faaf18
  13. Removing intermediate container f2c0ac021247
  14. Step 3 : WORKDIR todo
  15.  —> Running in c2d9cd32c182
  16.  —> 4e0029de9074
  17. Removing intermediate container c2d9cd32c182
  18. Step 4 : RUN npm install > /dev/null
  19.  —> Running in 79122dbf9e52
  20. npm WARN package.json [email protected] No repository field.
  21.  —> 9b6531f2036a
  22. Removing intermediate container 79122dbf9e52
  23. Step 5 : EXPOSE 8000
  24.  —> Running in d1d58e1c4b15
  25.  —> f7c1b9151108
  26. Removing intermediate container d1d58e1c4b15
  27. Step 6 : CMD npm start
  28.  —> Running in 697713ebb185
  29.  —> 74f9ad384859
  30. Removing intermediate container 697713ebb185
  31. Successfully built 74f9ad384859

以上的构建镜像步骤没有使用到缓存,每一层的镜像ID都与之间的不同。