~/post/how-docker-build-works
Published on

How docker build Really Works ?

2 mins read
Authors

If you run docker build, you need to understand what's happening under the hood. Itโ€™s not magic โ€” it's a clever use of containers themselves.

Hereโ€™s the breakdown ๐Ÿ‘‡

What really happens during docker build?

When Docker builds an image, it reads your Dockerfile line by line. But hereโ€™s the key: not every instruction creates a new layer.

1. For instructions that change the filesystem (RUN, COPY, ADD): Docker performs a three-step process for each one:

  • It spins up a temporary container using the image from the previous step.
  • It runs the command (e.g., RUN apt-get update) or copies the files inside that container.
  • It commits the result as a new image layer that contains only the filesystem changes.

2. For instructions that only change metadata (WORKDIR, ENV, CMD, EXPOSE):

  • No container is created. Docker simply updates the image's metadata (the config.json file) to be used by containers later on. These steps are incredibly fast because they don't involve creating layers.

Your final image is an ordered stack of these layers plus a final configuration.

So, how can a container run without an image?

To run a container, a low-level runtime like runc just needs an OCI bundle:

  • ๐Ÿ“ A root filesystem (a directory with all the necessary files).
  • ๐Ÿ“ A config.json file (specifying what command to run, environment variables, etc.).

That's it. A Docker image is essentially a convenient, portable way to package and distribute this bundle.

The Twist ๐Ÿ’ก

So, to build an image, Docker runs a series of temporary containers. But to run a container, you don't actually need an image โ€” just the final root filesystem and config file.

When Docker builds an image, it needs containers to run each instruction and commit the result as a new image layer.

But when you have a bundle ready, you can run a container without ever building a Docker image.

Understanding how docker build works under the hood:

  • Helps you debug weird build issues
  • Helps you order Dockerfile instructions for better caching
  • Explains why multi-stage builds are so powerful
  • Makes you appreciate the layered, file-system-based model of containers

Next time you type docker build, remember: you're running containers to build other containers.

Inspired by the excellent iximiuz article: You need containers to build an image.