Skip to content

Instantly share code, notes, and snippets.

@uraimo
Last active July 3, 2021 21:53
Show Gist options
  • Save uraimo/ae74a15f7ad69240f5b2a55a9cd87db8 to your computer and use it in GitHub Desktop.
Save uraimo/ae74a15f7ad69240f5b2a55a9cd87db8 to your computer and use it in GitHub Desktop.

How to squash an image with multiple layers in a single new one (losing history).

Enable experimental features in Docker

Using --squash requires a Docker with and API version greater than 1.13 (can be checked with docker version).

Edit /etc/docker/daemon.json adding:

  {
      "experimental": true
  }

Then restart Docker.

Squash

Create a Dockerfile in an empty directory:

  FROM yourimage:version
  RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

And then run build with the squash command:

  sudo docker build --squash -t yourNEWimage:NEWversion .

Done, way faster than exporting an images and importing it back.

Cleanup

Remove the old images with:

 docker rm oldimage:version

This will untag some images and generate stuff that can be purged with:

  docker system prune

When squash doesn't work

If squash doesn't work for your image, for example generating a "error squashing image: error getting tar stream to parent: layer ID xxxxxxxxxxx is not a parent of the specified layer: cannot provide diff to non-parent" try with the old method, save to a tar and import:

  docker save image:version -o tarfile
  docker import tarfile newimage:version

Way slower but it always works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment