Optimizing the Docker image size

Docker images are generated instruction by instruction from the Dockerfile. Though perfectly correct, many images are sub-optimized when we're talking about size. Let's see what we can do about it by building an Apache Docker container on Ubuntu 16.04.

Getting ready

To step through this recipe, you will need a working Docker installation.

How to do it…

Take the following Dockerfile, which updates the Ubuntu image, installs the apache2 package, and then removes the /var/lib/apt cache folder. It's perfectly correct, and if you build it, the image size is around 260 MB:

FROM ubuntu:16.04
RUN apt-get update -y
RUN apt-get install -y apache2
RUN rm -rf /var/lib/apt
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

Now, each layer is added on top of the previous. So, what's written during the apt-get update layer is written forever, even if we remove it in the last RUN.

Let's rewrite this Dockerfile using a one-liner, to save some space:

FROM ubuntu:16.04
RUN apt-get update -y && 
    apt-get install -y apache2 && 
    rm -rf /var/lib/apt/
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

This image is exactly the same, but is only around 220 MB. That's 15% space saved!

Replacing the ubuntu:16.04 image with the debian:stable-slim image gets the same result, but with a size of 135 MB (a 48% reduction in size!):

FROM debian:stable-slim
RUN apt-get update -y && 
    apt-get install -y apache2 && 
    rm -rf /var/lib/apt/
ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

How it works…

Each layer is added to its predecessor. By combining all the related commands from download to deletion, we keep a clean state on this particular layer. Another good example is when the Dockerfile downloads a compressed archive; downloading it, uncompressing it, and then removing the archive uses a lot of added layer space when done separately. The same in one line does everything at once, so instead of having the cumulated space taken from the archive and its uncompressed content, the space taken is only from the uncompressed content alone. Often, there's a very nice gain in size!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.85