Building docker images is pretty easy thanks to dockerfiles. But building small docker images is not always easy.
The cache mechanism is really powerful, but it’s also the main problem when dealing with image size optimization.
Let’s take an example and let’s see how to improve the dockerfile to improve the image size.
A Dockerfile as example
Base image size
As you can see we are using ubuntu 14.04 as the base image.
This base image size is 188.3 MB.
The image already has 5 layers.
More packages, elasticsearch, npm, and a PHP project (Satisfy)
The image size is now 703.4 MB
The image has 15 layers.
Optimization of the dockerfile
We do not need all recommended packages, so we can add the option --no-install-recommends to the apt-get install command.
We can clean apt and remove temporary files.
Add and remove archives or installers in the same layer
Change chmod on the same layer
Use prestissimo with Composer
Minimize image size
Drastically improve composer install runtime
After all those optimizations:
The image size is now 561.1 MB
The image has 11 layers.
Remove application cache and temporary files and directories
The image size is now 533.7 MB
All command in a single RUN
Be careful, because only complete RUN instruction can be cached.
So if you RUN everything in a single RUN, you could (maybe) not use cache as you should.