Images, layers and the Dockerfile

Junior Always asked 8 min

On this page

The question

What is the difference between a Docker image and a container?

30-second answer

An image is a read-only template: a stack of layers holding a filesystem, built from a Dockerfile, plus metadata such as the command to run. A container is a running instance of an image: the runtime adds a thin writable layer on top and starts the process in its own namespaces. Many containers can run from one image and share its layers. Delete a container and its writable layer goes with it, so data that must survive belongs in a volume.

Understand it

Order a Dockerfile for cache hits

Build

Order the Dockerfile so that changing a Java file reruns as few steps as possible. Each row shows whether it would come from the cache.

Drag a piece, or select it and then select a place.

View as text

Six Dockerfile instructions in rows, each marked cached or rerun for a change to the Java source only, with a line at the bottom counting the steps that rerun. Order the Dockerfile so that changing a Java file reruns as few steps as possible. Each row shows whether it would come from the cache.

The right order is: FROM maven:3.9-eclipse-temurin-21, because first: every layer builds on the base image. WORKDIR /app, because sets the folder the next steps use. COPY pom.xml ., because only the build file: it changes rarely. RUN mvn dependency:go-offline, because downloads dependencies, cached until pom.xml changes. COPY src ./src, because source changes on every commit, so it comes late. RUN mvn package -DskipTests, because compiles the jar after any source change.

Least changing first: base image, build file, dependencies, then the source. A code change now reuses the dependency layer and reruns only the copy and the build. If the source is copied before the dependencies are downloaded, every code change downloads them again.

Six Dockerfile instructions in rows, each marked cached or rerun for a change to the Java source only, with a line at the bottom counting the steps that rerun. Order the Dockerfile so that changing a Java file reruns as few steps as possible. Each row shows whether it would come from the cache.

The right order is: FROM maven:3.9-eclipse-temurin-21, because first: every layer builds on the base image. WORKDIR /app, because sets the folder the next steps use. COPY pom.xml ., because only the build file: it changes rarely. RUN mvn dependency:go-offline, because downloads dependencies, cached until pom.xml changes. COPY src ./src, because source changes on every commit, so it comes late. RUN mvn package -DskipTests, because compiles the jar after any source change.

Least changing first: base image, build file, dependencies, then the source. A code change now reuses the dependency layer and reruns only the copy and the build. If the source is copied before the dependencies are downloaded, every code change downloads them again.

Takeaway: Each instruction is a cached layer, reused until its input changes; then it and every later step run again. So put what changes rarely first and the source last.

A multi-stage build shrinks the image

Step by step

A single-stage image ships everything the build needed: the JDK, Maven, every downloaded dependency and the source. About 690 MB to push, pull and patch.

Step 1 of 6
View as text

Two columns of image layers, each drawn as a stack with its size in MB. The left column is the build stage, the right one the runtime stage, and a line at the bottom gives the size of the image that ships. The sizes are rounded figures for a typical Spring Boot service.

A single-stage image ships everything the build needed: the JDK, Maven, every downloaded dependency and the source. About 690 MB to push, pull and patch.

Split it. Stage 1, named build, starts from the JDK and Maven image and produces app.jar. Nothing in it ships unless a later stage copies it.

Stage 2 starts from a fresh, smaller base: a JRE (Java Runtime Environment), which runs bytecode but cannot compile it. No Maven, no source, no build tools.

COPY --from=build copies one file out of stage 1: app.jar. Everything else the build needed stays behind.

Only the last stage becomes the image: about 295 MB instead of 690, with fewer packages to patch and to attack. The build stage stays in the local cache.

Extract the Spring Boot jar into layers and copy each one separately, dependencies first. A code change now rebuilds and pushes only the small application layer.

Two columns of image layers, each drawn as a stack with its size in MB. The left column is the build stage, the right one the runtime stage, and a line at the bottom gives the size of the image that ships. The sizes are rounded figures for a typical Spring Boot service.

A single-stage image ships everything the build needed: the JDK, Maven, every downloaded dependency and the source. About 690 MB to push, pull and patch.

Split it. Stage 1, named build, starts from the JDK and Maven image and produces app.jar. Nothing in it ships unless a later stage copies it.

Stage 2 starts from a fresh, smaller base: a JRE (Java Runtime Environment), which runs bytecode but cannot compile it. No Maven, no source, no build tools.

COPY --from=build copies one file out of stage 1: app.jar. Everything else the build needed stays behind.

Only the last stage becomes the image: about 295 MB instead of 690, with fewer packages to patch and to attack. The build stage stays in the local cache.

Extract the Spring Boot jar into layers and copy each one separately, dependencies first. A code change now rebuilds and pushes only the small application layer.

Takeaway: Build in a stage with the JDK and Maven, then copy only the jar into a stage that starts from a small JRE. Only the last stage ships, so the image loses the build tools and the source.

An image is read-only layers; a container adds one writable layerdocker build turns a Dockerfile into an image made of read-only layers, one per instruction that changes files. docker run starts containers from that image. Each container adds its own thin writable layer on top, which is deleted with the container, while the image layers are shared by all of them.docker builddocker rundocker rundocker rmDockerfileImage:read-only layersContainer 1:+ writable layerContainer 2:+ writable layerWritable layerdeleted
An image is read-only layers; a container adds one writable layerdocker build turns a Dockerfile into an image made of read-only layers, one per instruction that changes files. docker run starts containers from that image. Each container adds its own thin writable layer on top, which is deleted with the container, while the image layers are shared by all of them.docker builddocker rundocker rundocker rmDockerfileImage:read-only layersContainer 1:+ writable layerContainer 2:+ writable layerWritable layerdeleted
An image is read-only layers; a container adds one writable layer

In code

FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
# Cached until pom.xml changes
RUN mvn -B dependency:go-offline
COPY src ./src
RUN mvn -B package -DskipTests

# A JRE (Java Runtime Environment): no JDK, no Maven, no source
FROM eclipse-temurin:21-jre
RUN useradd --system --uid 10001 app
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
# Never run as root
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
A multi-stage build for a Spring Boot service, ready for production
FROM eclipse-temurin:21-jre AS extract
WORKDIR /build
COPY target/*.jar application.jar
RUN java -Djarmode=tools -jar application.jar extract --layers --destination extracted

FROM eclipse-temurin:21-jre
WORKDIR /app
# Least changing first: a code change rebuilds only the last layer
COPY --from=extract /build/extracted/dependencies/ ./
COPY --from=extract /build/extracted/spring-boot-loader/ ./
COPY --from=extract /build/extracted/snapshot-dependencies/ ./
COPY --from=extract /build/extracted/application/ ./
ENTRYPOINT ["java", "-jar", "application.jar"]
Spring Boot layers: dependencies and code in separate image layers
docker build -t orders:1.4.2 .
# => CACHED [build 4/6] RUN mvn -B dependency:go-offline     <- reused: pom.xml did not change
# => [build 5/6] COPY src ./src                                <- a Java file changed: this step and later rerun

docker history orders:1.4.2            # one row per layer, with the instruction and the size it added
docker image inspect --format '{{index .RepoDigests 0}}' orders:1.4.2
# registry.example.com/orders@sha256:5f1c...  <- deploy this: a tag can move, a digest cannot

cat .dockerignore                      # target/  .git/  *.log   kept out of the build context
See the cache at work, the layers of an image, and its immutable digest
# Any change, even to README.md, invalidates COPY . . and every dependency downloads again
FROM maven:3.9-eclipse-temurin-21 AS build
 Wrong COPY . .
 Wrong RUN mvn -B package

# The build file first, its dependencies in their own layer, the source last
FROM maven:3.9-eclipse-temurin-21 AS build
 Right COPY pom.xml .
 Right RUN mvn -B dependency:go-offline
 Right COPY src ./src
 Right RUN mvn -B package -DskipTests
COPY . . before the build busts the cache on any file change
Does the builder reuse this layer?For each instruction in order, the builder checks whether the layer before it came from the cache and whether the instruction is unchanged. For COPY and ADD it also compares the checksums of the copied files. If all match, it reuses the cached layer; otherwise it runs the instruction, and every later instruction runs again too.noyesnoyesnoyesNext instructionPrevious layerfrom cache?Run it, and everystep after itSame instructiontext?COPY or ADD:same filechecksums?Reuse thecached layer
Does the builder reuse this layer?For each instruction in order, the builder checks whether the layer before it came from the cache and whether the instruction is unchanged. For COPY and ADD it also compares the checksums of the copied files. If all match, it reuses the cached layer; otherwise it runs the instruction, and every later instruction runs again too.noyesnoyesnoyesNext instructionPrevious layerfrom cache?Run it, and everystep after itSame instructiontext?COPY or ADD:same filechecksums?Reuse thecached layer
Does the builder reuse this layer?

Solve it

Every CI build downloads all Maven dependencies again

A team’s image build takes six minutes in CI. The Dockerfile starts from a Maven image, runs COPY . . and then mvn package. The log shows Maven downloading hundreds of artifacts on every build, even when only one Java file changed. Make the build fast without changing what the image contains.

  1. Find the first miss. Read the build output: every step up to COPY . . says CACHED. That copy changes whenever any file in the context changes, so mvn package, and its downloads, never hit the cache.
  2. Split by change rate. Copy pom.xml alone, run mvn dependency:go-offline, then copy src. Dependencies now sit in a layer that is reused until the build file changes.
  3. Shrink the context. Add a .dockerignore for target/, .git/ and IDE files, so a local build or a Git operation cannot invalidate a layer and the context uploads faster.
  4. Keep the cache across runners. A fresh CI runner has no local cache. Push and pull it with --cache-from and --cache-to on a registry, or mount Maven’s repository as a BuildKit cache, which survives even a pom change.
  5. Check. Change one Java file and rebuild: the dependency step says CACHED, no artifacts download, and the build takes the time of the compile only.
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
RUN --mount=type=cache,target=/root/.m2 mvn -B dependency:go-offline
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 mvn -B package -DskipTests

FROM eclipse-temurin:21-jre
COPY --from=build /app/target/*.jar /app/app.jar
ENTRYPOINT ["java", "-jar", "/app/app.jar"]

# CI: docker buildx build --cache-from type=registry,ref=registry.example.com/orders:cache \
#       --cache-to type=registry,ref=registry.example.com/orders:cache,mode=max -t orders:1.4.2 .
Dependencies in their own layer, plus a cache mount for Maven's repository

How to answer

  • Image is to container as class is to object.
  • Layers are content-addressed and shared between images and containers.
  • Images are immutable; build a new image instead of changing a running container.
  • Tags name an image and can move; a digest pins one exact image.

Common mistakes

  • Fixing a running container with docker exec and calling it deployed, instead of building a new image.
  • Storing a database's files in the container's writable layer.

Follow-up questions

How do image layers and the build cache work?

Each Dockerfile instruction that changes files, such as RUN, COPY and ADD, adds a layer. When building, the builder reuses a cached layer if the step before it was cached and the instruction is unchanged; for COPY and ADD the copied files' checksums must match too. The first step that misses runs again, and so does every step after it. So order instructions from least to most often changed: base image, dependencies, then source.

  • A cache miss cascades to every later instruction.
  • RUN apt-get update alone is cached forever; combine it with the install in one RUN.
  • .dockerignore keeps target/, .git/ and secrets out of the context and the cache key.

See it in the infographic: Order a Dockerfile for cache hits

What is a multi-stage build, and why use one?

A Dockerfile with several FROM lines. Earlier stages hold the build tools: a JDK (Java Development Kit), Maven and the source, which compile the jar. The last stage starts from a small runtime base, such as a JRE, and copies only the artifact with COPY --from. Only the last stage becomes the image, so it is several times smaller, has fewer packages to patch and no source code or build secrets, while the build itself stays reproducible in one file.

  • Name stages with AS and copy from them by name.
  • docker build --target build stops at a stage, for tests or debugging.
  • BuildKit builds independent stages in parallel and skips unused ones.

See it in the infographic: A multi-stage build shrinks the image

What makes a good Docker image for a Java service?

A multi-stage build that ships a JRE, not a JDK, from a small, maintained base with a pinned version. Order layers for the cache, with dependencies before code, or use Spring Boot's layered jar. Run as a non-root user, start java with the exec form of ENTRYPOINT so it receives SIGTERM, and size the heap with -XX:MaxRAMPercentage rather than a fixed -Xmx. Keep secrets out of the image, scan it for CVEs (Common Vulnerabilities and Exposures), and deploy by digest.

  • Buildpacks, with mvn spring-boot:build-image, or Jib build a good image without a Dockerfile.
  • A HEALTHCHECK or Kubernetes probes, backed by the Actuator health endpoint.
  • Distroless or Alpine bases shrink the image; jlink can build a custom, smaller JRE.

See it in the infographic: A multi-stage build shrinks the image

What is the difference between CMD and ENTRYPOINT?

ENTRYPOINT is the executable the container runs; CMD gives its default arguments, or the whole default command when there is no ENTRYPOINT. Arguments after the image name in docker run replace CMD, while ENTRYPOINT is only replaced with --entrypoint. Write both in exec form, a JSON array, so the process is PID (process ID) 1 and gets signals; the shell form wraps it in /bin/sh -c.

  • ENTRYPOINT java -jar app.jar with CMD --spring.profiles.active=prod gives a fixed program with overridable flags.
  • COPY copies local files; ADD also fetches URLs and unpacks archives, so prefer COPY.
  • RUN runs at build time; CMD and ENTRYPOINT run when the container starts.

See it in the infographic: Order a Dockerfile for cache hits

Why should production not deploy the latest tag?

Because a tag is a movable name. latest, or even 1.4, can point to a different image tomorrow, so two nodes pulling the same tag may run different code, and a rollback to latest rolls back nothing. Tag every build with an immutable version, such as the Git commit or a release number, and pin deployments to that tag or, better, to the image digest, sha256:..., which identifies exactly one image.

  • A digest is a hash of the image manifest; it cannot change.
  • Kubernetes pulls a latest tag on every start by default, an imagePullPolicy of Always.
  • Base images in FROM can be pinned by digest too, with a bot to update them.

See it in the infographic: A multi-stage build shrinks the image

Two containers run from the same 300 MB image. How much disk do they use?

About 300 MB plus whatever each one writes. The image layers are stored once and shared read-only; each container only adds its own writable layer, which holds the files it creates or changes, copied up from the layer below on first write.

What is in an image besides files?

A configuration: the entrypoint and command, environment variables, the working directory, the user, exposed ports, labels and the ordered list of layer digests. A manifest ties it together, and for multi-platform images an index lists one manifest per CPU architecture. All of it follows the OCI (Open Container Initiative) image format.

Check yourself

1. A Dockerfile copies pom.xml, runs mvn dependency:go-offline, copies src, then runs mvn package. You change one Java file and rebuild. What runs again?
Show answers
  • COPY src and mvn package: Correct. COPY src is the first step whose input changed; it and every later step rerun.
  • Every step from FROM onward: Incorrect. Steps before the first changed input come from the cache.
  • Only mvn package: Incorrect. COPY src itself misses first, because the copied files' checksums changed.
2. Same Dockerfile. This time you add a dependency to pom.xml. Which step is the first to run again?
Show answers
  • COPY pom.xml: Correct. Its file changed, so it misses, and so does every step after it.
  • mvn dependency:go-offline: Incorrect. It reruns too, but only because COPY pom.xml before it missed first.
  • COPY src: Incorrect. The source is unchanged, but the steps before it already missed.
3. A two-stage build compiles with Maven in stage build, then starts FROM eclipse-temurin:21-jre and copies the jar with COPY --from=build. What does the final image contain?
Show answers
  • The JRE base layers and the jar: Correct. Only the last stage becomes the image; COPY --from brings just the jar across.
  • Maven, the source and the jar: Incorrect. Those stay in the build stage, which is not shipped.
  • Only the jar: Incorrect. The final stage also keeps its own base image, the JRE.