11

I have build a docker image by making incremental commits. This has led to the creation of a lot of layers in my docker image and subsequently the size of the image has gone very large.

Is there a way to remove the layers and as a result reduce the size of the image ?

Any help would be appreciated.

Aaquib Khwaja
  • 544
  • 3
  • 7
  • 14
  • 2
    You'll find the process much more efficient, repeatable, and controllable to build with a Dockerfile instead of incremental commits. – BMitch Apr 15 '19 at 18:00

2 Answers2

11

You could try to export the image and then import it again. By doing it this way all the layers will be lost and your image size will be lower.

sudo docker export red_panda > exampleimage.tar
cat exampleimage.tar | sudo docker import - exampleimagelocal:new

Note that this only works with containers, so you will need to launch one from the image and then do the trick.

Hope it helps.

Jorge Marey
  • 558
  • 4
  • 10
  • I exported the image, and then imported it on a different machine. I wasn't able to run that image on that machine. It said "unable to find image locally". What might be the issue ? – Aaquib Khwaja May 18 '15 at 08:51
  • Hi, which command did you use to import it? Did you use the same image name for the import and the run command? If you execute `docker images` does the image lists there? – Jorge Marey May 19 '15 at 07:20
  • Can you execute `docker images` to see if the imported image is listed? – Jorge Marey May 20 '15 at 09:56
  • I have a message: docker: Error response from daemon: pull access denied for xxxreduce, repository does not exist or may require 'docker login'. – user3345547 Oct 23 '19 at 12:47
7

You can squash layers with next trick

FROM oracle AS needs-squashing
ENV NEEDED_VAR some_value
COPY ./giant.zip ./somewhere/giant.zip
RUN echo "install giant in zip"
RUN rm ./somewhere/giant.zip

FROM scratch
COPY --from=needs-squashing / /
ENV NEEDED_VAR some_value
Ryabchenko Alexander
  • 10,057
  • 7
  • 56
  • 88
  • 2
    there's a one issue with this approach - if you have environment variables from the container from previous layer that are required for it to work, and you go with `FROM scratch` approach as you have presented here, the variables are not retained - for example you can lose `$JAVA_HOME` due to that - so use with care! – tymik Dec 19 '19 at 15:21