Docker Tip #3: Chain Your Docker RUN Instructions to Shrink Your Images
You might be doing things in your Dockerfile that are causing your images to be bloated. Here's 1 strategy for shrinking them.
There’s lots of ways to shrink your images but an easy win is to make use of Docker’s built in caching mechanisms for when it comes to building images.
For example, let’s say you wanted to do these 3 things:
- Use
wget
to download a zip file from somewhere - Extract the zip file to a directory of your choosing
- Remove the zip file since it’s not needed
You could do it the inefficient way by adding this to your Dockerfile
:
RUN wget -O myfile.tar.gz http://example.com/myfile.tar.gz
RUN tar -xvf myfile.tar.gz -C /usr/src/myapp
RUN rm myfile.tar.gz
That’s going to bloat your image and make 3 separate layers because there’s
3 RUN
instructions. It’s bloated because myfile.tar.gz
is now a part of your
image when you do not need it.
Instead, you could chain things together like a Docker pro by doing:
RUN wget -O myfile.tar.gz http://example.com/myfile.tar.gz \
&& tar -xvf myfile.tar.gz -C /usr/src/myapp \
&& rm myfile.tar.gz
This is much better. Docker will only create 1 layer, and you still performed all 3 tasks. Shrinkage! You’ll even get faster build times too because each layer adds a bit of build time.