What Are Image Layers in Docker?

What Are Image Layers in Docker?

A beginner-friendly guide to the stacked building blocks inside every Docker image, and why understanding them makes your builds faster, your downloads smaller, and your containers safer.

Imagine you are baking a cake with several tiers. The bottom tier is a plain sponge. On top of it goes a layer of jam, then a layer of cream, and finally a layer of icing. Now suppose a friend wants the same cake but with different icing. You do not bake everything again from scratch. You reuse the sponge, the jam, and the cream, and you only swap the top. Docker images work in exactly this way. Each image is a stack of layers, and each layer is one tier of the cake. Because layers can be reused, Docker saves time, saves space, and saves bandwidth every single day.

1Why Do Layers Exist?

To appreciate layers, first imagine life without them.

Suppose that every Docker image were one single, giant file. You build an application, and Docker packs the operating system files, the programming language, your libraries, and your own code into one huge block. Now imagine you have fifty applications, and forty of them use the same operating system files and the same language runtime. With a single-block design, you would store the same operating system fifty times. Every download would repeat the same gigabytes. Every tiny code change would force a brand-new giant block to be built and shipped.

That would be wasteful and slow. Developers change their own code many times a day, but the operating system underneath changes rarely. It makes no sense to rebuild and resend the rarely changing parts each time. Docker solves this by cutting an image into layers, where each layer holds only one small set of changes. Layers that stay the same are reused. Only the layers that changed need to be rebuilt or sent.

This one design decision is behind many of Docker’s best qualities: fast builds, quick downloads, small storage use, and the ability for hundreds of containers to share the same base. When you understand layers, you understand why Docker feels so fast compared with older ways of packaging software.

Simple Analogy

Think of a stack of transparent sheets, like the old overhead projector slides used in classrooms. Each sheet has a small drawing on it. When you stack them and look from above, you see one complete picture. If you want a different picture, you swap just one sheet instead of redrawing all of them.

Stacked
layers pile up to form one image
Read-only
once built, a layer never changes
Shared
many images and containers reuse the same layers

2Some Words You Need First

A small glossary will make the rest of this guide easy to read.

Term 1

Image

A read-only package that contains an application and everything it needs to run. It is the recipe from which containers are made.

Term 2

Layer

One building block of an image. It records a set of file changes, such as files added, modified, or removed.

Term 3

Container

A running instance of an image, with a thin writable layer added on top for its own temporary changes.

Term 4

Dockerfile

A plain text recipe that lists the steps for building an image. Each step can create a new layer.

Term 5

Base Image

The image you start from, usually a small operating system or a language runtime. Its layers form the bottom of your stack.

Term 6

Digest

A long fingerprint, calculated from the content of a layer or image. Same content always gives the same fingerprint.

Term 7

Registry

An online library where images and their layers are stored, so any machine can download them.

Term 8

Cache

A memory of earlier work. Docker remembers layers it has already built so it can skip repeating them.

i
Keep This in Mind

An image is a stack of read-only layers. A container is that same stack plus one thin writable layer on top. If you remember only this sentence, you already understand the heart of Docker storage.

3So, What Exactly Is an Image Layer?

A layer is a recorded set of changes to the file system, packed into a single unit.

An image layer is a snapshot of the differences made to the files of an image at one step of its construction. It does not contain a complete copy of everything. It contains only what changed compared with the layer below it. Perhaps a layer adds a set of new programs. Perhaps another adds your application files. Perhaps a third changes a single settings file. Each of these is stored as its own layer.

Behind the scenes, a layer is stored as a compressed archive of files, together with a fingerprint that identifies it. Once a layer is created, it is never edited. It is read-only and permanent. If something needs to change, Docker does not go back and alter the old layer. It creates a new layer on top that records the change. This keeps every layer trustworthy and reusable.

Layers Are About Differences

The idea of storing only differences is the secret to saving space. Think about a document with ten versions. You could keep ten full copies, or you could keep one original and a note for each version saying what was changed. The second approach uses far less space. Layers work like those notes. The bottom layer holds a base set of files, and each layer above it records what was added, changed, or removed.

Simple Analogy

Consider a shared family photo album where each new page shows only the new additions to a growing family portrait. The first page shows the parents. The next page adds the first child. The next adds the second child. To see the whole family, you flip through the pages together. No page repeats what an earlier page already shows.

!
Common Misconception

Many beginners picture a layer as a small independent program or a mini image. It is not. A layer is only a set of file changes, and it usually makes no sense on its own. It gains meaning only when stacked with the layers beneath it.

4What an Image Is Made Of

An image is more than a pile of layers. It has a few small companion pieces.

When Docker stores or ships an image, it treats it as a small collection of parts. Understanding these parts explains how Docker knows which layers belong to which image and in what order to stack them.

Part 1

The Layers

The actual file changes, stored as compressed archives. They make up almost all of the size of an image.

Part 2

The Configuration

A small description of the image: what command to run, which environment settings to use, and the ordered list of layer fingerprints.

Part 3

The Manifest

A table of contents that names the configuration and each layer, so a registry and a client agree on exactly what the image contains.

Part 4

The Tag

A friendly, human-readable name such as a version label. It is only a pointer to a manifest and can be moved to point elsewhere.

graph TD
  T["Tag: friendly name"] --> M["Manifest: table of contents"]
  M --> C["Configuration: settings and layer order"]
  M --> L1["Layer 1: base system files"]
  M --> L2["Layer 2: language runtime"]
  M --> L3["Layer 3: application libraries"]
  M --> L4["Layer 4: your application code"]
        
FIG 1 — The manifest ties together the configuration and the ordered layers of an image

Notice that the tag sits at the very top. A tag is only a label stuck onto a manifest. The same image can carry several tags, and a tag can be moved from one image to another. The layers and the fingerprints below it are the true, unchanging identity of the image.

Simple Analogy

Think of a recipe book. The tag is the title on the cover, the manifest is the table of contents, the configuration is the note about how to serve the dish, and the layers are the actual ingredient lists. The title can be reprinted, but the ingredients define what you really cook.

5How a Dockerfile Creates Layers

Layers are not created randomly. They come directly from the steps of your build recipe.

A Dockerfile is a list of instructions read from top to bottom. Some of these instructions change the files inside the image, and those create a real layer. Other instructions only record information, such as which command should run when a container starts, and those add a small piece of settings without adding meaningful file content.

Instructions That Add Real Layers

Adds a Layer

The Base Choice

Choosing a starting image brings in all of that image’s layers as the bottom of your stack.

Adds a Layer

Run a Command

Executing a command, such as installing software, records every file that the command changed as a new layer.

Adds a Layer

Copy Files

Copying files from your project into the image records those files as a new layer.

Adds a Layer

Add Files

A close cousin of copying, which can also fetch remote files or unpack archives, and records the result as a layer.

Instructions That Only Record Settings

Instructions that set an environment value, choose a working folder, declare a port, add a label, or define the default start command mostly record metadata. They are stored in the image configuration, and they take up essentially no space. They matter for how the container behaves, but they do not add files to the stack.

1

Start from a base image

Docker brings in the layers of the chosen base. These form the foundation of your stack.

2

Run a setup command

Docker starts a temporary container, runs the command, and saves all resulting file changes as a new layer.

3

Copy in your files

Docker records your application files as another new layer above the previous ones.

4

Record settings

Docker writes down the start command and environment values in the configuration, without adding meaningful file content.

5

Finish the image

Docker seals the stack, calculates fingerprints, and produces the final image ready to run or share.

flowchart TD
  A["Base image layers"] --> B["Step: install software"]
  B --> C["New layer: installed files"]
  C --> D["Step: copy application files"]
  D --> E["New layer: application code"]
  E --> F["Step: set start command"]
  F --> G["Settings only, no new files"]
  G --> H["Finished image"]
        
FIG 2 — Each file-changing step becomes a layer, while settings-only steps add no file content
i
A Useful Habit

Every time you write a build step, ask yourself, “What files will this step add, change, or remove?” That question tells you exactly what the resulting layer will contain and helps you keep images tidy.

6How Layers Combine Into One Picture

Stacked layers must be shown to a container as one ordinary, complete file system. A clever technology makes this possible.

When a container starts, it must see a single normal set of folders and files, as if nothing were layered at all. The tool that creates this illusion is called a union file system. Its job is to take many separate layers and present them as one merged view. On modern Linux systems, Docker normally uses a storage driver named overlay2, which is built on a kernel feature for exactly this purpose.

The rules of the merged view are simple. When the container looks for a file, the system searches from the top layer down to the bottom. The first layer that contains that file wins, and the container sees that version. Lower layers that also contain the same file are hidden beneath it. If a higher layer marks a file as removed, the file appears deleted, even though it still exists in a lower layer.

graph TD
  W["Container writable layer: temporary changes"] --> A["Image layer 4: application code"]
  A --> B["Image layer 3: libraries"]
  B --> C["Image layer 2: runtime"]
  C --> D["Image layer 1: base system"]
  W -.-> V["Merged view seen by the container"]
  A -.-> V
  B -.-> V
  C -.-> V
  D -.-> V
        
FIG 3 — The union file system merges every layer into a single view for the container
Simple Analogy

Look down through a stack of glass panes, each painted with part of a scene. Where an upper pane has paint, you see that paint. Where it is clear, you see through to the pane below. The combined view looks like one painting even though it is many panes working together.

The Three Folders Behind the Scenes

Under the hood, overlay2 uses three ideas. The lower folders hold the read-only image layers. The upper folder is the writable layer that belongs to the specific container. The merged folder is the combined view that the container actually sees. You rarely touch these directly, but knowing they exist makes the whole system feel much less mysterious.

7The Writable Layer and Copy-on-Write

Image layers are read-only, so where do a running container’s changes go?

When Docker starts a container from an image, it adds one extra layer on top of the stack. This layer is thin, empty at first, and writable. Anything the running application creates, changes, or deletes is recorded in this top layer. The image layers below are never touched. This is what lets a hundred containers share the same image without interfering with one another: each gets its own private writable layer on top of the same shared base.

What Is Copy-on-Write?

Sometimes a container needs to modify a file that lives in a lower, read-only layer. The system cannot edit the file in place, because that layer is shared. Instead, it uses a strategy called copy-on-write. The first time the container tries to change the file, the system quietly copies that file up into the container’s writable layer, and the change is applied to the copy. From then on, the container sees the modified copy, and the original in the lower layer remains untouched for everyone else.

Simple Analogy

Imagine a shared library book that nobody may write in. If you want to make notes, you photocopy the page and write on your own copy. Everyone else still sees the clean original in the book. Copy-on-write is the same idea, and it protects shared layers from accidental changes.

sequenceDiagram
  participant App as Application in container
  participant W as Writable layer
  participant L as Read-only image layers
  App->>W: Ask to modify a file
  W->>L: Is the file here?
  L-->>W: Yes, found in a lower layer
  W->>W: Copy the file up into the writable layer
  W-->>App: Change applied to the copy
        
FIG 4 — Copy-on-write: a file is copied up to the writable layer the first time it is changed
!
Important Warning

The writable layer is destroyed when its container is removed. Any data written there disappears with the container. Anything you need to keep, such as a database, must be stored in a volume, which lives outside the layers entirely.

Because copy-on-write copies whole files, writing heavily to large files inside a container’s writable layer can be slow. This is another reason why volumes are recommended for data-heavy work: they bypass the layered system and talk to the disk more directly.

8Fingerprints: How Layers Are Identified

Every layer has a unique identity based on what it contains, not on what someone decided to call it.

Docker identifies each layer by a digest, which is a long fingerprint calculated from the layer’s contents using a strong mathematical method. The idea is simple. If two layers contain exactly the same files, they produce exactly the same fingerprint. If even a single byte differs, the fingerprint is completely different.

This approach is called content-addressable storage, meaning that content is found by what it is rather than by a name. It has powerful consequences. Because identical content has an identical fingerprint, Docker can recognize that two images use the same layer, and store that layer only once on disk. It can also verify that a downloaded layer has not been damaged or tampered with, simply by recalculating the fingerprint and comparing.

Benefit 1

Automatic Deduplication

Two images that share a base layer store it only once. The more images share, the more space is saved.

Benefit 2

Integrity Checking

A changed or corrupted layer no longer matches its fingerprint, so the problem is caught immediately.

Benefit 3

Reliable References

A manifest can name exact fingerprints, so it always points to precisely the content that was tested.

Benefit 4

Efficient Transfers

A machine can compare fingerprints and download only the layers it does not already have.

Simple Analogy

Think of a fingerprint at a police station. It does not matter what name someone gives; the fingerprint identifies the person uniquely. Layer fingerprints identify content in the same way, regardless of what anyone calls it.

i
Tags Versus Digests

A tag such as a version label can be moved to point at a different image tomorrow. A digest never changes for a given piece of content. For maximum repeatability in production, referring to an image by its digest guarantees you get exactly the same thing every time.

9Layers on the Move: Pulling and Pushing

Layers make downloading and uploading images remarkably efficient.

When you ask Docker to download an image, it first fetches the manifest, which lists all the layer fingerprints. Then, for each layer, Docker checks whether that fingerprint already exists on your machine. If it does, the layer is skipped. Only the missing layers are downloaded, and they can be downloaded at the same time to save time. This is why the second image you pull from the same family is usually much faster than the first.

Uploading works the same way in reverse. When you send an image to a registry, Docker asks the registry which layers it already holds. Only the layers the registry lacks are uploaded. If you have changed only the top layer that contains your application code, only that small layer travels across the network, even though the image as a whole may be hundreds of megabytes.

sequenceDiagram
  participant M as Your machine
  participant R as Registry
  M->>R: Request image manifest
  R-->>M: List of layer fingerprints
  M->>M: Compare with layers already stored
  M->>R: Request only the missing layers
  R-->>M: Send missing layers
  M->>M: Verify fingerprints and assemble the image
        
FIG 5 — Pulling an image: only the layers you do not already have are downloaded
Skip
layers you already have
Parallel
missing layers download together
Verified
each layer checked by its fingerprint
Simple Analogy

Suppose you are updating a large encyclopedia set. The publisher does not send you all volumes again. They compare what you own with the new edition and mail only the new or changed volumes. Docker’s layer transfer follows the same sensible idea.

10The Build Cache: Reusing Layers to Build Faster

Layers are the reason a second build can finish in seconds instead of minutes.

When Docker builds an image, it remembers every layer it has produced. On the next build, it walks through your recipe from the top. For each step, it asks a simple question: “Is this exactly the same step as last time, sitting on top of exactly the same layers, with exactly the same input files?” If the answer is yes, Docker reuses the stored layer and skips the work. This is called a cache hit.

The moment Docker meets a step that differs from before, it must build that step again. And here is the crucial rule: once one step is rebuilt, every step after it must also be rebuilt, because each later layer sits on top of the changed one. The cache is valid only as a continuous chain from the top of the recipe down to the first change.

flowchart TD
  A["Step 1: base image"] --> B{"Same as last build?"}
  B -- Yes --> C["Reuse cached layer"]
  B -- No --> X["Rebuild this and every later step"]
  C --> D["Step 2: install dependencies"]
  D --> E{"Same as last build?"}
  E -- Yes --> F["Reuse cached layer"]
  E -- No --> X
  F --> G["Step 3: copy application code"]
  G --> H{"Files changed?"}
  H -- Yes --> Y["Rebuild only this and later steps"]
  H -- No --> Z["Reuse cached layer"]
        
FIG 6 — Docker reuses cached layers until it meets the first changed step, then rebuilds from there

The Golden Rule of Ordering

Because a change invalidates everything after it, the order of your steps matters enormously. Steps that rarely change, such as installing the operating-system tools and the project’s dependencies, should come first. Steps that change often, such as copying your own application code, should come last. That way, an everyday code change invalidates only the final layer, and the expensive earlier layers are reused from the cache.

Simple Analogy

When building a house, you do not repaint the walls before laying the foundation. You put the stable, slow work at the bottom and the fast, changeable finishing touches on top. If the paint color changes, you repaint only the walls, and the foundation stays exactly as it is.

i
Practical Tip

Bring in the file that lists your project’s dependencies first and install them, and only afterwards copy the rest of your code. Then, when you edit your source files, the slow dependency step is served from the cache and your build takes seconds.

11The Deleted-File Trap

One of the most surprising facts about layers is that removing a file in a later layer does not make the image smaller.

Because layers are read-only and permanent, a later layer cannot truly erase something that an earlier layer already contains. When a later step deletes a file, Docker records a special marker, sometimes called a whiteout, in the new layer. This marker tells the merged view to hide the file. The file disappears from what the container sees, but its bytes still sit inside the lower layer, and they are still downloaded, stored, and shipped with the image.

Imagine a step that downloads a large installer, another step that uses it to install a program, and a third step that deletes the installer. The final image looks clean, yet the layer that first added the installer still carries all its bytes. The image is just as large as if the deletion never happened. Many beginners are baffled when a cleanup step fails to shrink the image.

ANTI-PATTERN-01 Avoid
Problem

Downloading temporary files in one build step and deleting them in a separate, later step, expecting the image to shrink.

Why It’s Harmful

The deletion only hides the files. The earlier layer still contains them, so the image stays large, downloads take longer, and storage is wasted.

Correct Approach

Do the download, use, and cleanup inside the same build step, so the temporary files never get saved in any layer. Or use a multi-stage build so that temporary material never reaches the final image at all.

Simple Analogy

Imagine writing in a notebook with permanent ink. You cannot erase a mistake, but you can draw a box around it and write “ignore this.” Readers no longer see it as part of the story, but the ink is still on the page, and the notebook is just as heavy.

12Making Layers Smaller and Smarter

A handful of simple techniques keep images lean and builds fast.

Technique 1

Choose a Small Base

Starting from a slim base image avoids carrying hundreds of megabytes of tools you will never use. Minimal bases can be only a few megabytes.

Technique 2

Combine Related Steps

Join steps that belong together, such as install and cleanup, into one step so temporary files never land in a saved layer.

Technique 3

Use Multi-Stage Builds

Build your application in one stage that has all the heavy tools, then copy only the finished result into a small final stage.

Technique 4

Ignore Unneeded Files

Use an ignore file to keep notes, test data, and version-control folders out of the build so they never enter a layer.

Technique 5

Order Steps Wisely

Put stable steps first and fast-changing steps last, so the cache works for you instead of against you.

Technique 6

Install Only What You Need

Skip optional packages and recommended extras. Each unnecessary tool adds size and a possible security weakness.

Multi-Stage Builds in Plain Words

A multi-stage build is like cooking in a messy workshop and then serving in a clean dining room. In the first stage, you use a large image with compilers and build tools to produce your finished application. In the final stage, you start from a tiny clean image and copy in only the finished product. None of the workshop clutter, meaning the compilers, temporary files, and source code, ever makes it into the shipped layers.

flowchart LR
  A["Stage 1: large build image with heavy tools"] --> B["Compile and produce the finished application"]
  B --> C["Copy only the result"]
  C --> D["Stage 2: small clean runtime image"]
  D --> E["Final image: lean and secure"]
        
FIG 7 — A multi-stage build ships only the finished result, leaving the heavy tools behind
!
Balance Matters

Do not obsess over reducing the number of layers at any cost. Fewer layers can mean worse caching, because a change to any part of a combined step rebuilds the whole step. Aim for a sensible balance: group steps that belong together, and keep fast-changing steps separate.

13Security and Layers

Because layers are permanent, whatever goes into them stays there.

The permanence of layers has an important security consequence. If a password, a key, or any secret ever enters a layer, it remains in that layer forever, even if a later step deletes it. Anyone who can download the image can unpack its layers one by one and read the secret. Deleting it in a later layer only hides it from the final merged view, not from the layer archive itself.

ANTI-PATTERN-02 Avoid
Problem

Copying passwords, access keys, or private certificates into an image during the build, and removing them in a later step.

Why It’s Harmful

The secret remains stored inside an earlier layer and can be extracted by anyone who obtains the image. Publishing such an image to a public registry can leak credentials to the whole world.

Correct Approach

Never place secrets in the image. Use the build system’s secret-handling feature for build-time needs, and supply runtime secrets to the container from a protected source when it starts.

Other Security Points

Point 1

Smaller Means Safer

Every extra program in a layer is another thing that may contain a security bug. Lean layers mean a smaller attack surface.

Point 2

Scan Every Layer

Security scanners examine layers for known vulnerable software. A weakness in a base layer affects every image built on it.

Point 3

Trust the Source

Base layers come from someone else. Prefer official, well-maintained images from sources you trust.

Point 4

Rebuild for Fixes

Layers are frozen in time. To receive security fixes for a base, you must rebuild your image on top of an updated base.

The fingerprint system helps here too. Because each layer’s digest is derived from its content, you can verify that the layers you run are exactly the ones that were tested and scanned. Any silent tampering would change the fingerprint and be detected.

14Looking Inside: Inspecting and Monitoring Layers

You can see the layers of an image and watch how much disk they use.

Docker provides tools to look at how an image was constructed. A history view lists every step that contributed to an image, in order, along with the size each step added. This is the fastest way to discover which step is responsible for a bloated image. You will often spot a single step that added hundreds of megabytes, and that tells you exactly where to focus your effort.

An inspection view shows the image’s configuration and the list of layer fingerprints. Community tools also exist that let you browse each layer’s file changes visually, showing what was added, modified, or removed at every step. These are excellent for learning and for hunting wasted space.

Watching Disk Usage

Layers accumulate quietly. Every image you pull, every build you run, and every intermediate result adds to disk usage. Docker has a summary view that reports how much space is used by images, containers, volumes, and build cache, and how much of it could be reclaimed. Dangling layers, which are layers no longer referenced by any tagged image, are a common source of wasted space after many rebuilds.

Signal 1

Image History

Shows each build step and how many bytes it added, revealing which layers are the largest.

Signal 2

Image Inspection

Reveals the configuration and the ordered list of layer fingerprints that make up the image.

Signal 3

Disk Usage Summary

Reports space used by images, containers, volumes, and cache, and what can be safely reclaimed.

Signal 4

Dangling Layers

Unreferenced layers left behind by rebuilds. Clean them up regularly to free space.

i
Helpful Habit

Whenever an image feels too big, look at its history first. The step with the largest size is almost always the best target, and fixing one or two steps often shrinks an image dramatically.

15Strengths and Trade-offs of Layers

The layered design brings big benefits and a few costs worth knowing about.

Advantages

  • Shared layers are stored once, saving large amounts of disk space
  • Only changed layers are rebuilt, making repeated builds very fast
  • Only missing layers are downloaded or uploaded, saving bandwidth and time
  • Hundreds of containers can share the same read-only base safely
  • Fingerprints let Docker verify integrity and detect tampering
  • Every step of an image’s history is visible and auditable

Disadvantages / Trade-offs

  • Deleted files still occupy space in earlier layers
  • Secrets that enter a layer remain readable forever
  • Poor step ordering makes the build cache nearly useless
  • Copy-on-write can be slow for heavy writing to large files
  • Too many layers, or very large ones, can slow pulls and complicate management
“A layer never forgets: whatever you put into one stays there, even if a later layer hides it.”

16Comparing Layers With Neighboring Ideas

A table to keep layers, images, containers, and volumes clearly separate in your mind.

ConceptWhat It IsCan It Change?Lifetime
Image layerA set of file changes stored as one unitNo, read-only and permanentStays until no image uses it and it is cleaned up
ImageAn ordered stack of layers plus configurationNo, a new build makes a new imageUntil you remove it
Container writable layerA thin top layer private to one containerYes, this is where changes happenRemoved when the container is removed
VolumeA storage area managed outside the layersYes, freelySurvives container removal
Build cacheRemembered layers from previous buildsRebuilt when inputs changeUntil pruned
Virtual machine diskA full separate virtual disk with its own operating systemYes, entirely writableLives as long as the virtual machine

Layers Versus a Virtual Machine Disk

A traditional virtual machine stores its entire operating system on a single, fully writable virtual disk. Ten identical virtual machines usually mean ten full copies of the disk. Docker layers avoid that duplication by sharing the read-only parts and keeping only tiny writable layers per container. That difference is one of the main reasons containers are so much lighter than virtual machines.

17Real-World Examples

Layers quietly power many everyday situations.

A Team With Many Small Services

A company runs fifty small services, and forty of them are built on the same language runtime image. Thanks to layer sharing, that runtime is stored once on each server, not forty times. Deploying a new service only needs the small layer holding its own code.

A Fast Automated Build Pipeline

An automation system builds a new image every time a developer saves a change. By ordering the recipe well and keeping a shared cache, the slow dependency layers are reused and each build finishes in seconds rather than minutes.

A Rapid Rollout During Heavy Traffic

When traffic spikes, new servers join a cluster and must fetch the application image. Because most layers are already present on a server or cached nearby, only a few layers download, and new capacity comes online quickly.

A Security Team Reacting to a Weakness

A serious bug is found in a popular base layer. Scanners use layer information to list every image built on it, so the team knows exactly which applications to rebuild on an updated base.

A Student Learning on a Laptop

A learner pulls several images that all start from the same small base. After the first download, the rest come quickly and use little extra disk space, which makes experimenting cheap and comfortable.

18Patterns and Anti-Patterns

Habits that make images lean, and habits that quietly bloat them.

Helpful Patterns

Stable First, Volatile Last

Arrange your recipe so rarely changing steps come first and frequently changing ones come last. This gives the best cache behavior and the smallest rebuilds.

Shared Base Images Across a Company

Have a company-approved base image that many teams reuse. Every team benefits from shared layers, consistent security patching, and predictable behavior.

Separate Build From Run

Use one stage or image for building and a different, minimal one for running. The running image should contain only what is needed at run time.

Anti-Patterns to Avoid

ANTI-PATTERN-03 Avoid
Problem

Copying the entire project folder into the image at the very first step, before installing dependencies.

Why It’s Harmful

Any tiny edit to any file changes the early layer and invalidates the cache for every step after it, forcing slow dependency installation on every build.

Correct Approach

Copy only the dependency list first and install, then copy the rest of the code afterwards, so ordinary edits only affect the final layers.

ANTI-PATTERN-04 Avoid
Problem

Using a huge general-purpose base image for a tiny application, and leaving build tools inside the final image.

Why It’s Harmful

The image is much larger than necessary, slower to transfer, and contains many extra programs that can hold security weaknesses.

Correct Approach

Pick a small base that suits the application and use a multi-stage build so only the finished result reaches the final image.

ANTI-PATTERN-05 Avoid
Problem

Storing important application data in the container’s writable layer instead of a volume.

Why It’s Harmful

The data disappears when the container is removed, and heavy writing is slower through copy-on-write than direct disk access.

Correct Approach

Keep all data that must last in volumes or an external storage service, and treat containers as disposable.

19Best Practices Checklist

A short list to keep your layers small, fast, and safe.

1

Start from a small, trusted base

A lean official base means fewer bytes to carry and fewer places for security bugs to hide.

2

Order steps from stable to volatile

Put slow, rarely changing work early and your own frequently edited code last to get maximum cache reuse.

3

Clean up in the same step that makes the mess

Remove temporary files within the same build step that created them so they never get saved into a layer.

4

Use multi-stage builds

Keep compilers and build tools out of the final image by copying only the finished output into a fresh stage.

5

Keep secrets out of every layer

Never copy passwords or keys into an image. Supply them safely at build time or run time through proper mechanisms.

6

Exclude unneeded files with an ignore file

Prevent notes, test data, and version-control folders from entering the build at all.

7

Pin base image versions or digests

Naming an exact version, or better a digest, keeps builds repeatable instead of drifting with a moving label.

8

Inspect history and clean regularly

Look at image history to find heavy steps, and periodically remove unused layers and old cache.

20Frequently Asked Questions

Q1What is an image layer in one sentence?

An image layer is a read-only record of the file changes made at one step of building an image, and Docker stacks many of these to form the complete image.

Q2Does every line in a Dockerfile create a layer?

No. Steps that change files, such as running a command or copying files, create real layers. Steps that only record settings, such as environment values or the default start command, add metadata but essentially no file content.

Q3Why did my image stay large after I deleted files?

Because the files still exist inside the earlier layer that added them. A later deletion only hides them in the merged view. Clean up within the same step that created the files, or use a multi-stage build.

Q4Can two images share the same layer?

Yes, and this is one of Docker’s biggest strengths. Layers with identical content have identical fingerprints and are stored only once on disk, no matter how many images use them.

Q5Where do a container’s changes go?

Into a thin writable layer that sits on top of the image layers. It belongs only to that container and is deleted when the container is removed.

Q6Why is my build so slow every time?

Often because an early step changes on each build and invalidates the cache for every step after it. Reorder your recipe so stable steps come first and frequently changing files are copied last.

Q7Is it better to have fewer layers?

Not always. Grouping related steps can reduce waste, but merging everything into one step ruins cache reuse. Aim for a balanced, sensible grouping rather than the smallest possible number.

Q8Are secrets safe if I delete them in a later step?

No. The secret stays inside the earlier layer and can be extracted by anyone with access to the image. Never place secrets in an image at all.

Q9Where do layers live on my computer?

In the Docker daemon’s data folder, which on Linux is by default under the location /var/lib/docker. Manage them through Docker’s own tools rather than editing that folder by hand.

Q10How is a layer different from a volume?

A layer is read-only content that is part of an image, or a temporary writable layer that dies with the container. A volume is a separate storage area that survives container removal and is meant for data you want to keep.

21Summary and Key Takeaways

A Docker image is not one solid block. It is a neat stack of read-only layers, each recording a small set of file changes made by one step of the build. A union file system merges the layers into one clean view, and a thin writable layer on top lets each running container make its own private changes through copy-on-write. Fingerprints identify layers by their content, which lets Docker store shared layers only once, verify their integrity, and move only the missing pieces across the network. The build cache reuses unchanged layers to make repeat builds fast, but only when steps are ordered wisely. Because layers are permanent, deleted files still cost space and secrets never truly disappear. By choosing small bases, ordering steps carefully, cleaning up in the same step, and using multi-stage builds, you turn layers from a mystery into a powerful ally.

Key Takeaways

  • An image is a stack of read-only layers — each layer records the file changes from one build step, and together they form the complete image.
  • Layers are shared and stored once — identical layers have identical fingerprints, saving disk space, build time, and download time.
  • A container adds one thin writable layer — copy-on-write protects shared layers, and the writable layer is lost when the container is removed, so use volumes for data.
  • Step order controls the build cache — put stable steps first and fast-changing steps last, because a change invalidates every layer after it.
  • Deleting later does not shrink earlier layers — clean up within the same step that creates temporary files, or use multi-stage builds.
  • Secrets in a layer are there forever — never copy passwords or keys into an image, even if a later step deletes them.
  • Inspect and clean regularly — use image history to find heavy steps and remove unused layers so your disk stays healthy.