If there are RUN commands in docker file then it does create some intermediate images. My question is whether such intermediate images occupy any memory of your hard drive? If yes, docker build --rm
should be enough?
-
memory or space? – sandpat Jan 23 '20 at 05:01
-
You might find [What are Docker image "layers"?](https://stackoverflow.com/questions/31222377/what-are-docker-image-layers) enlightening. – David Maze Jan 23 '20 at 10:46
-
1`docker images -f "dangling=true"` shows all those intermediary layers, and yes, they occupy disk space. – Jan 23 '20 at 11:21
2 Answers
Yes intermediate layers occupy disk space and it is a good thing usually. This facilitates re-use of layers and speedy builds. What you should be concentrating on instead is to reduce the number of layers by optimising the dockerfile. Your final docker image is actually a combination of all the layers. So you cannot remove the layers unless you remove the final image and no other image is using the layers.
docker build --rm
does not save any extra disk space. To understand why, you should know how docker build
works - Each instruction (e.g., RUN) in a dockerfile starts a new container, after the instruction completes, the container exits, and is committed to an image.
docker build --rm
removes these intermediate containers. --rm
option is true by default and so docker build --rm
has not extra affect compared to docker build
. For some reason if you want to keep the intermediate containers then you can turn it off with --rm=False
.
If there are any layers which are not being used by any other images, you can remove them. These are called dangling
layers. You can remove them with following command -
docker rmi $(docker images -f "dangling=true" -q)

- 10,007
- 2
- 25
- 41
RUN
does not create intermediate images, but intermediate layers/containers.
If you run docker build --rm
these containers will be deleted after they're generated, so yes it will save space in your disk but will need more time each time you rebuild the same image, since it will create those layers everytime as they are not cached.
Edit (thanks @Shashank V): The --rm
option is set by default, so having it or not makes no difference.

- 1,366
- 1
- 10
- 26
-
1This is not entirely true. `--rm` option is default with `docker build` and it is not going to save any extra space. `--rm` is only to remove the intermediate containers and the layers still saved to disk. So it is not going to save any disk space and rebuilding is not going to take any extra time as the layers are still cached. – Shashank V Jan 24 '20 at 06:48
-
You're right - there's no difference as it's the default behaviour. But it saves space either way. Only if you set it to false you occupy disk space. – samthegolden Jan 24 '20 at 10:19