Time for #DEVDiscuss — right here on DEV 😎
Dockerfile Optimization using Multistage Builds, Caching, and Lightweight images
Internet Explorer ・ May 30 '23
#docker
#programming
#kubernetes
#laravel
Inspired by @er_dward's Top 7 post, tonight’s topic is...optimizing Dockerfiles 🐳
According to the post...
Leveraging Docker's caching mechanism and multistage builds can result in significant enhancements in Dockerfile efficiency for a Laravel PHP application using Yarn and Nginx. With a better understanding of these mechanisms, developers can craft Dockerfiles that build faster, produce smaller images, and thus, reduce resource usage.
Questions:
- What tools, tips, and tricks have you used to optimize Dockerfiles?
- Have you used any non-Docker solutions for efficient container development?
- Any triumphs, fail whales, or other stories you'd like to share on this topic?
Top comments (3)
One thing people often forget: installing packages/dependencies will (generally) keep download caches that are totally useless at runtime:
npm ci,pip install, etc. but alsoapt-get.One thing I like to do: use BuildKit's
--mountonRUNstages to put those cache dirs outside the image. You can use acachemount to keep those between builds, ortmpfsmounts for truely volatile storage.Do the same with
bindmounts instead ofCOPYing a file to process and delete it in a followingRUN(such as copying an archive to then extract and delete it)Also, use Dive to analyse your images and find bloat. Not only those files overwritten in a subsequent layer (that Dive automatically detects), but also those files you shouldn't have added to your layers (such as those download caches)
I wrote a blog post a while ago about optimizing the size (and also build speed) of the containers for AWS Lambdas written in Rust:
Building Super Slim Containerized Lambdas on AWS
Ervin Szilagyi for AWS Community Builders ・ Sep 14 '22 ・ 7 min read
Some obvious tricks and tips:
Yes, while I was writing my other blog post:
Containers: Under the Hood
Ervin Szilagyi for AWS Community Builders ・ Oct 15 '22 ・ 15 min read
I used Podman and LXC/LXD.
I guess 2 blog posts should be enough, although, I have even more stories for anybody interested. :)