Docker Images, Layers & the Dockerfile

~12 min read

How a Dockerfile becomes a versioned, cacheable image, and why layer order matters for build speed.

A Dockerfile is a text file of instructions (FROM, COPY, RUN, CMD, etc.) that Docker executes in order to build an image. Each instruction produces a new filesystem layer, and Docker caches layers — if a layer's inputs haven't changed since the last build, Docker reuses the cached layer instead of rebuilding it, which is why Dockerfiles are typically written with rarely-changing instructions (installing dependencies) before frequently-changing ones (copying application code): if you copy code first and dependencies second, every code change invalidates the dependency-install cache and forces a slow reinstall on every build. An image is the immutable stack of layers; a container is a running instance of that image with one additional writable layer on top for runtime changes, which is discarded when the container stops (unless you mount a persistent volume).

💻 Code example

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]

💬 Deep Dive with AI

Key points

  • Each Dockerfile instruction creates a cacheable layer
  • Order instructions from least-frequently-changing to most-frequently-changing for faster builds
  • An image is immutable layers; a container adds one writable layer on top
  • Images are tagged (e.g. myapp:1.2.0) and pushed to a registry like ECR for orchestrators to pull