使用Dockerfile构建镜像可以利用它的缓存功能:只有在命令已更改的情况下,才会重建已构建的步骤。下面是重新构建之前涉及到的to-do app的示例:
- $ docker build .
- Sending build context to Docker daemon 2.56 kB
- Sending build context to Docker daemon
- Step 0 : FROM node
- —> 91cbcf796c2c
- Step 1 : MAINTAINER [email protected]
- —> Using cache
- Indicates you’re using the cache
- Specifies the cached image/layer ID
- —> 8f5a8a3d9240
- Step 2 : RUN git clone -q https://github.com/docker-in-practice/todo.git
- —> Using cache
- —> 48db97331aa2
- Step 3 : WORKDIR todo
- —> Using cache
- —> c5c85db751d6
- Step 4 : RUN npm install > /dev/null
- —> Using cache
- —> be943c45c55b
- Step 5 : EXPOSE 8000
- —> Using cache
- —> 805b18d28a65
- Step 6 : CMD npm start
- —> Using cache
- —> 19525d4ec794
- 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构建镜像。
- $ docker build –no-cache .
- Sending build context to Docker daemon 2.56 kB
- Sending build context to Docker daemon
- Step 0 : FROM node
- —> 91cbcf796c2c
- Step 1 : MAINTAINER [email protected]
- —> Running in ca243b77f6a1
- —> 602f1294d7f1
- Removing intermediate container ca243b77f6a1
- Step 2 : RUN git clone -q https://github.com/docker-in-practice/todo.git
- —> Running in f2c0ac021247
- —> 04ee24faaf18
- Removing intermediate container f2c0ac021247
- Step 3 : WORKDIR todo
- —> Running in c2d9cd32c182
- —> 4e0029de9074
- Removing intermediate container c2d9cd32c182
- Step 4 : RUN npm install > /dev/null
- —> Running in 79122dbf9e52
- npm WARN package.json [email protected] No repository field.
- —> 9b6531f2036a
- Removing intermediate container 79122dbf9e52
- Step 5 : EXPOSE 8000
- —> Running in d1d58e1c4b15
- —> f7c1b9151108
- Removing intermediate container d1d58e1c4b15
- Step 6 : CMD npm start
- —> Running in 697713ebb185
- —> 74f9ad384859
- Removing intermediate container 697713ebb185
- Successfully built 74f9ad384859
以上的构建镜像步骤没有使用到缓存,每一层的镜像ID都与之间的不同。