Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #3: Chain Your Docker RUN Instructions to Shrink Your Images

docker-tips-and-tricks.jpg

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:

  1. Use wget to download a zip file from somewhere
  2. Extract the zip file to a directory of your choosing
  3. 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.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments