Docker
--squash
containerization
DevOps
image optimization

How does the new Docker --squash work

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Docker is an open-source platform prevalent for creating, shipping, and running applications inside containers. It helps developers to debug applications consistently across different environments by ensuring that applications behave the same irrespective of where they are deployed. As Docker evolves, new features are added, and one such feature is the `--squash` flag. This flag is used to reduce the size of Docker images by squashing intermediate image layers. Here, we'll explain how the `--squash` feature works, its implications, and provide technical examples to help users better understand its utility.

Overview of Docker Image Layers

Before we dive into the `--squash` flag, it's important to understand Docker image layers. Every command in a Dockerfile (e.g., `RUN`, `COPY`) typically creates a new image layer. These layers build upon each other to form the final Docker image. Layers help in:

  • Efficiency: If a layer hasn't changed, Docker can reuse it, speeding up builds.
  • Cache: Layers act as a cache, meaning subsequent builds are typically faster if consecutive commands have not changed.

However, each layer adds to the total image size, which can become inefficient for distribution.

The Purpose of `--squash`

The `--squash` flag was introduced to address the problem of bloated images caused by multiple intermediate layers. By squashing, Docker combines those layers into a single layer, thereby reducing the image size and hiding the intermediate steps. This is particularly useful for production images, where the focus is more on size and less on layer introspection.

How Docker `--squash` Works

By using the `--squash` option, Docker takes all layers and merges them into a single layer. This collapse reduces the image's size but sacrifices the caching benefits of individual layers. Below, we detail the mechanics of squashing:

  • The Docker daemon creates the image as usual, building each layer step by step.
  • Once complete, Docker melds all layers from the base image onwards into one.
  • If a parent image is specified, squashing happens from that parent layer onwards. If not, all layers merge except the base image.

Example

Here’s a Dockerfile to illustrate:


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.