Putting paketo images on a diet
If you haven’t heard about paketo buildpacks by now I recommend you to take a look at it before continuing. TL:DR; Paketo buildpacks are the next generation of cloud-native technology with full support for the majority of programming languages. At the time of writing this post, you can create a cloud-ready image of a Laravel project using pack, a command-line utility used to create cloud-native buildpacks.
The problem
Not really a problem but rather an undesired situation that needs to be addressed is that the images generated for PHP projects are pretty chunky. The size is due to the fact the builder used for PHP projects contains many other libraries needed to support not only PHP but other programming languages, you could say the builder has some extra weight on it.
Possible solutions
- You could roll up your own builder
- You could, (once you build the image) extract the source code and put it on a new image using crane
- Or you could minify the image using docker-slim
I’m going to choose the third option because personally, I don’t have the time to create my own builder, and using crane seems like an extra step compared with docker-slim.
Minification
Let’s first create a base scenario. In this case a fresh new Laravel application.
1) Make sure you have installed the pack CLI
# There are multiple ways to install it depending on your OS. Check this link for reference https://buildpacks.io/docs/tools/pack/brew install buildpacks/tap/pack
2) Create a Laravel application using composer, then pack it. Hold on, it might take a while especially if this is the first time.
composer create-project laravel/installer paketo-php && \
cd paketo-php && \
pack build paketo-php --buildpack gcr.io/paketo-buildpacks/php --builder paketobuildpacks/builder:full
Take a look at the generated image, a Laravel application weighing 874MB.
REPOSITORY TAG IMAGE ID CREATED SIZE
paketo-php latest 48ba4a5c7531 41 years ago 874MB
If we apply docker slim to it by running:
docker-slim build -http-probe --env PORT=8080 --publish-port 8080 --expose 8080 api
we obtain the same fully functional image prefixed with .slim
being 9x lighter than the original.
REPOSITORY TAG IMAGE ID CREATED SIZE
paketo-php latest 95f17a312750 16 seconds ago 103MB
Final Words
The image size has always been a consideration in the release and usage of containerized products. Knowing the tools and better when to apply them will put your work at its prime. In this post, we see how to minify an OCI image generated by pack but you could apply the same process for traditional Dockerfile-based images.