Size and clean-up

Finding where image weight comes from and cleaning the disk without losses.

If an image is unexpectedly large, docker history shows the size of every layer and the instruction that created it. The culprit is usually obvious at once: copying a whole folder with node_modules, a package manager cache, or a file deleted in the next instruction.

docker history notes-api:0.1
# CREATED BY                                SIZE
# CMD ["python" "main.py"]                  0B
# COPY . .                                  86MB
# RUN pip install --no-cache-dir -r ...    41MB

Here you can see that COPY . . added 86 MB: most likely extra files ended up in the context and need to be added to .dockerignore.

Deleting a file in a separate instruction does not make the image smaller: the file stays in the previous layer, and the new layer only marks it as deleted. That is why temporary files are created and deleted in the same RUN instruction, and package manager caches are turned off with flags such as --no-cache-dir for pip or --no-cache for apk.

Over time the disk fills up with old images, stopped containers and build cache. docker system df shows how much space each category takes. docker image prune removes dangling images without a tag, docker container prune removes stopped containers, and docker builder prune removes build cache. These commands do not touch volumes.

A common mistake is to run docker system prune -a --volumes to “free everything”. The -a flag removes every image without a running container, so the next start downloads them all again, and --volumes removes volumes together with their data. On a server, clean up one category at a time and always look at the list of what will be removed before confirming.

Practice

  1. Where the weight comes from

    Which command shows the size of every image layer and the instruction that created it?

    • docker ps
    • docker history
    • docker logs
    • docker stats
  2. Image size

    Which statements about image size are true? Mark all.

    • RUN rm in a separate instruction makes the final image smaller
    • Temporary files are deleted in the same RUN instruction that created them
    • pip's --no-cache-dir flag makes the dependency layer smaller
    • .dockerignore helps to avoid copying extra files
  3. How much is used

    Which command shows how much disk space images, containers, volumes and build cache take?