Skip to content

    System Design

    Docker and Containers: Images, Layers and Build Cache

    Learn what images and containers are, how layers and the build cache work, how to package a Spring Boot service as a layered image, and runtime habits.

    By Published 13 min read

    Share

    Standard lessonbeginnerSpring Boot labBackend System Design

    What you'll learn: By the end of this lesson you will be able to explain what an image, a container and a registry are, say how layers and the build cache decide how fast a build is, read a multi-stage Dockerfile for a Spring Boot service and explain why its layers are ordered the way they are, name the production habits that matter (a non-root user, exec-form entry point, pinned base images, memory limits), and say honestly what a Compose file does and does not do.

    A shipping container is a standard steel box. The port does not care whether it holds bananas or machine parts: it lifts, stacks and moves every box the same way. Before the box, every cargo needed its own handling. After it, the contents became the sender's problem and the movement became everyone's.

    A software container is the same bargain. You package a service together with the files it needs, and any machine with a container engine can start it the same way. This lesson teaches the packaging: what an image is made of, why layers matter for build speed, and how a Spring Boot service is packaged well. Kubernetes core objects covers running many of them.

    Verified on 2026-12-01 against the Docker and Spring Boot documentation pages listed at the end. The Dockerfile and Compose file below are shown as written and were not run, because no container engine was available. The lab that does run examines the layered jar inside the image, not an image.

    The core idea

    An image is a package of everything a container needs to start, and a container is an ordinary process that runs from that image in isolation. Docker's overview says an image is "a package of everything a container needs to start" and that "once built, an image never changes". A container is "an ordinary process on your computer ... that runs in isolation".

    Two consequences follow. Because an image never changes, you do not patch a running container: you build a new image and replace the container. And because an image is built from cacheable layers, the order of the build decides how much a one-line code change costs.

    Three illustrations run through the lesson, each labelled:

    • Minimal example: the four instructions of a simple Dockerfile and what each becomes.
    • Realistic example: the ShopStream catalogue service packaged as a layered Spring Boot image.
    • Failure example: a shell-form entry point that never receives the stop signal.

    Image, container and registry

    An image is built from a Dockerfile, "a text document that contains all the commands a user could call on the command line to assemble an image". A registry is "a service that stores images so anyone with access can pull them". A container is what you get when you start an image. Containers "don't copy the image": they share its layers, and each gets "its own writable layer", so a second container from the same image is cheap and its writes stay out of the image.

    From Dockerfile to running containersDockerfile to Image (docker build); Image to Registry (push); Registry to Containers (pull, run)Dockerfile: build recipeDockerfilebuild recipeImage: read-only layersImageread-only layersRegistry: stores imagesRegistrystores imagesContainers: share the layersContainersshare the layersdocker buildpushpull, run

    Figure 1. The life of an image. How to read this: you build once and push to a registry. Every machine that needs the service pulls the same image and starts as many containers as it wants. The image does not change; the containers come and go.

    What "isolation" means

    Docker's security page says kernel namespaces provide "the first and most straightforward form of isolation": processes in a container "cannot see, and even less affect, processes running in another container", and each container gets its own network stack. Control groups (cgroups) "implement resource accounting and limiting", so a single container cannot exhaust a resource and bring the system down. By default a container has no resource constraints, which is why limits matter and why you set them yourself.

    Layers and the build cache

    Each Dockerfile instruction "translates to a layer in your final image", and "you can think of image layers as a stack". Docker caches layers, with one rule that explains almost every slow build: "whenever a layer changes, that layer will need to be re-built", and "if a layer changes, all other layers that come after it are also affected".

    Minimal example (illustrative). Four instructions, each a layer:

    FROM bellsoft/liberica-openjre-debian:25-cds
    WORKDIR /application
    COPY app.jar app.jar
    ENTRYPOINT ["java", "-jar", "app.jar"]

    FROM "initializes a new build stage and sets the base image". WORKDIR sets the directory for the instructions after it. COPY brings files from the build context into the image. ENTRYPOINT sets the main command. The build context is "the set of files that your build can access", and a .dockerignore file can "exclude files or directories from the build context", so files such as secrets or build output need not reach the build at all.

    The ordering rule has a practical reading: put what changes rarely first and what changes often last. If the application jar is copied in one COPY, every code change replaces the layer holding dozens of library jars along with your few classes.

    flowchart TD accTitle: A changed layer invalidates every layer after it accDescr: A stack of four image layers from base image to application code. When the dependencies layer changes, the dependencies layer and the application layer after it are rebuilt, while the base layers below it are reused from cache. When only the application layer changes, only that one layer is rebuilt. A["Layer 1: base image"] --> B["Layer 2: libraries"] B --> C["Layer 3: application code"] B -. "library changes: layers 2 and 3 rebuild" .-> X["Rebuilt"] C -. "code changes: only layer 3 rebuilds" .-> Y["Rebuilt"]

    Figure 2. Order decides cache reuse. How to read this: the layers are a stack, with the least-changing at the top of the diagram. A change rebuilds its own layer and everything after it, so put the layer that changes most, your code, last.

    Packaging a Spring Boot service: the layered jar

    A Spring Boot executable jar bundles your classes and every library into one file. The Spring Boot reference says copying that "uber jar" as-is is "not optimal", because "you probably recompile your code more often than you upgrade the version of Spring Boot you use". Its remedy is a layer index: a file inside the jar that lists layers in the order they should be added to the image. The default layers are dependencies, spring-boot-loader, snapshot-dependencies and application, and the reference explains the design: "library code is less likely to change between builds", while "application code is more likely to change between builds so it is isolated in a separate layer".

    A tools mode of the jar splits it. java -Djarmode=tools -jar my-app.jar offers commands that include list-layers and extract, and extract --layers writes one directory per layer, so that each directory can become one COPY step.

    Realistic example (ShopStream catalogue service). A multi-stage Dockerfile following the sample in the Spring Boot reference:

    FROM bellsoft/liberica-openjre-debian:25-cds AS builder
    WORKDIR /builder
    ARG JAR_FILE=build/libs/*.jar
    COPY ${JAR_FILE} application.jar
    RUN java -Djarmode=tools -jar application.jar extract --layers --destination extracted
    
    FROM bellsoft/liberica-openjre-debian:25-cds
    WORKDIR /application
    COPY --from=builder /builder/extracted/dependencies/ ./
    COPY --from=builder /builder/extracted/spring-boot-loader/ ./
    COPY --from=builder /builder/extracted/snapshot-dependencies/ ./
    COPY --from=builder /builder/extracted/application/ ./
    USER 10001
    EXPOSE 8080
    ENTRYPOINT ["java", "-jar", "application.jar"]

    Not run. The base image tag and the extract commands come from the Spring Boot reference's sample, adjusted for a Gradle jar path. Four details deserve a sentence each:

    • Multi-stage. Each FROM starts a stage; COPY --from=builder takes files from an earlier stage, and "none of the build tools required to build the application are included in the resulting image".
    • Layer order. The four COPY steps follow the layer index, so the libraries come before the code and a code change reuses everything above it.
    • USER 10001. Docker advises: "if a service can run without privileges, use USER to change to a non-root user". The instruction accepts a user name or a UID.
    • EXPOSE 8080. It "doesn't actually publish the port"; it documents it. Publishing happens at run time, for example docker run -p 8080:8080.
    The catalogue image: one layer per COPYdependencies to application (COPY order); boot loader to application; snapshots to application; application to ENTRYPOINT (start)dependencies: changes rarelydependencieschanges rarelyboot loader: empty hereboot loaderempty heresnapshots: empty heresnapshotsempty hereapplication: changes every buildapplicationchanges everybuildENTRYPOINT: java -jarENTRYPOINTjava -jarCOPY orderstart

    Figure 3. The layers of the catalogue image. How to read this: the three upper layers are copied first and almost never change, so they come from cache. The application layer is last because it changes on every build. In the lab's extracted layout two of the layers hold no files.

    Build it

    The lab examples/spring-labs/labs/boot-layered-jar is small and runs with Gradle and a JDK, without Docker. It builds a tiny Spring Boot service with Spring Boot 4.1.2, then inspects the jar. It does not build an image or start a container; it does the one part of the build that needs no container engine. Run it with ./gradlew :labs:boot-layered-jar:test from examples/spring-labs; the test builds the jar, runs the two jar-mode commands from the Spring Boot reference, and compares the report with a golden file.

    Expected output, captured from a real run (the layer index inside the jar, then list-layers):

    == 1. The layer index inside the jar (BOOT-INF/layers.idx) ==
    - "dependencies":
      - "BOOT-INF/lib/"
    - "spring-boot-loader":
      - "org/"
    - "snapshot-dependencies":
    - "application":
      - "BOOT-INF/classes/"
      - "BOOT-INF/classpath.idx"
      - "BOOT-INF/layers.idx"
      - "META-INF/"
    
    == 2. java -Djarmode=tools -jar app.jar list-layers ==
    dependencies
    spring-boot-loader
    snapshot-dependencies
    application

    The index is written by the build and lists the layers in the order they should be added. It names directories rather than single files, which is why it differs from the file-by-file example in the reference. Next the lab runs extract --layers, appends one byte to the extracted application jar as a stand-in for a code change, and compares a SHA-256 fingerprint of each layer directory.

    Expected output, captured from a real run (extraction, the stand-in change, and the whole-jar comparison):

    == 3. extract --layers: what each COPY step would bring into the image ==
    dependencies           files=33
    spring-boot-loader     files=0
    snapshot-dependencies  files=0
    application            files=1
    application layer contents:
      boot-layered-jar-0.0.1-SNAPSHOT.jar
    dependencies layer holds 33 jars, including spring-boot-4.1.2.jar
    
    == 4. A stand-in code change: one byte appended to the application layer ==
    dependencies           unchanged: cache hit
    spring-boot-loader     unchanged: cache hit
    snapshot-dependencies  unchanged: cache hit
    application            changed: rebuilt
    
    == 5. The same change with the whole jar copied as one layer ==
    whole jar as one COPY: changed: rebuilt
    dependencies layer is 18.8 MiB; application layer is under 100 KiB: true

    Read what the run shows and what it does not. It shows that the 33 library jars (18.8 MiB) and the application jar are separate directories, so a change to the application leaves the library fingerprints identical. Docker's cache decides on the content of the files a COPY brings in, so unchanged directories should be cache hits; the labels "cache hit" and "rebuilt" in the output are that inference, not an observed Docker build. The one-byte change is a stand-in for a real rebuild. Two of the four layer directories hold no files in this extracted layout, because the application jar refers to the extracted library jars. No image, image size, registry or container exists in this lab. GoldenRunTest compares the whole report with golden/boot-layered-jar.txt.

    Running containers well

    Entry point in exec form. CMD "should almost always be used in the form of CMD ["executable", "param1", "param2"]". The Dockerfile reference explains why for ENTRYPOINT too: the shell form runs the command under a shell and "does not pass signals", so the executable does not receive them.

    Pin the base image. "To fully secure your supply chain integrity, you can pin the image version to a specific digest." Choose a base "built from a trusted source" that is kept small, and rebuild regularly so fixes in the base reach you.

    Set a memory limit and make the JVM aware of it. A container has no resource limit by default. docker run --memory sets "an upper limit on the memory available to the container", and if memory runs out "the kernel kills processes in a container". On Linux the Java runtime detects container limits by default: the java documentation says the VM then determines the memory and processors available in a container and "container support is enabled by default". Detecting the limit is not the same as leaving enough room: the heap is only part of what a JVM process uses, so set the heap size explicitly, leave headroom below the limit, and watch real use.

    Keep configuration out of the image. Pass settings with environment variables or mounted files at run time (docker run -e sets environment variables), so one image runs in every environment.

    Docker Compose for local development

    Compose describes a multi-container application in a compose.yaml file, the preferred default name. Its model has "services", "networks", "volumes", "configs" and "secrets". A minimal file for local work:

    services:
      catalogue:
        image: registry.example.com/shopstream/catalogue:1.4.0
        ports:
          - "8080:8080"
        environment:
          SPRING_PROFILES_ACTIVE: local

    Not run. Compose is a convenience for a laptop or a test rig, not a production scheduler. One limit is worth knowing: with depends_on, "Compose does not wait until a container is 'ready', only until it's running" unless you use the long syntax with condition: service_healthy and a healthcheck. A service that starts before its database accepts connections is the classic local failure.

    flowchart TD accTitle: Choosing what goes in a container image accDescr: A decision flow. Code and its libraries belong in the image. Settings that differ by environment are passed at run time. Secrets are injected at run time and never baked into a layer. State that must outlive a container goes to a volume or an external store. S["A file or value the service needs"] --> Q1{"Same in every
    environment?"} Q1 -->|yes| I["Put it in the image,
    in the right layer"] Q1 -->|no| Q2{"Sensitive?"} Q2 -->|yes| SE["Inject at run time,
    never bake into a layer"] Q2 -->|no| CF["Pass as environment
    variable or mounted file"] I --> Q3{"Must it survive the
    container?"} Q3 -->|yes| V["Use a volume or an
    external store instead"] Q3 -->|no| OK["Fine: containers
    are ephemeral"]

    Figure 4. What belongs in the image. How to read this: the image holds what is the same everywhere. Settings and secrets arrive at run time, and anything that must outlive a container lives outside it.

    Trade-offs

    Choice Gain Cost Wrong when
    Single fat-jar layer Simplest Dockerfile Every code change rebuilds and re-pushes the libraries Builds are frequent or the registry link is slow
    Layered jar, multi-stage Small changing layer, no build tools in the image A longer Dockerfile Build is a one-off
    Pinned digest Reproducible, supply-chain control You must update it deliberately Nobody owns base-image updates
    Compose One command to start a stack Not a scheduler: no scaling or rescheduling You need production orchestration
    Memory limit Caps a leak's damage Kill when set below real peak The limit is a guess

    In practice: packaging the catalogue service

    This is an educational scenario on ShopStream with illustrative numbers.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's catalogue service has a browsing peak of about 2,300 requests per second (the shared illustrative figure). Today it ships as a jar copied to virtual machines. The team will move to containers and wants builds that stay fast as the team commits many times a day, and images a Kubernetes cluster can run.

    Starting architecture

    Catalogue release today, starting architectureBuild server to Artifact store (upload); Artifact store to Catalogue VMs (copy by hand)Build server: makes a fat jarBuild servermakes a fat jarArtifact store: one jar per buildArtifact storeone jar per buildCatalogue VMs: copy and restartCatalogue VMscopy and restartuploadcopy by hand

    Options considered

    Option Gain Cost Wrong when
    A. One layer: copy the fat jar into an image Easiest to write Whole jar re-pushed on each build Commits are frequent
    B. Layered multi-stage image Only the application layer changes per build A longer Dockerfile to maintain The team will not read it
    C. B plus a pinned base digest and scheduled rebuilds Reproducible and patched A process to own There is no owner for base images

    The decision

    Option B now and C once an owner exists. The pipeline builds the jar, builds the image with the multi-stage Dockerfile above, runs as a non-root user, uses exec form, and tags with a version rather than a floating name. Settings arrive as environment variables and the database password is injected at run time. A memory limit is set after measuring.

    Rollout and verification

    Build the image twice after changing one source file and check which layers the build reports as reused. Start a container, call its health endpoint, and stop it with docker stop, confirming that shutdown logs appear. Run one instance beside the old VMs on a small share of traffic, then widen.

    The 2 a.m. failure

    Releases drop a few in-flight requests on every deployment and the stop takes ten seconds. A teammate rewrote the entry point in shell form to expand an environment variable.

    sequenceDiagram accTitle: A shell-form entry point does not pass the stop signal accDescr: The platform sends a stop signal to the container. The shell that started the Java process does not pass it on, so the Java process keeps serving. After a timeout the platform kills the container, dropping in-flight requests instead of finishing them. participant P as Platform participant S as Shell (PID 1) participant J as Java process P->>S: stop signal Note over S: shell form does not pass signals S--xJ: signal not delivered Note over J: keeps running, no graceful shutdown P->>S: timeout, then force kill Note over J: in-flight requests cut off

    First checks: read the Dockerfile's ENTRYPOINT and look for shell form. Mitigation: restore exec form, and if an environment variable must be expanded, do it through Spring's own property mechanism instead of the shell. Follow-up: add a release test that sends the stop signal and asserts a graceful-shutdown log line appears.

    Architect's notes

    • Order the Dockerfile by how often things change, libraries before code.
    • Treat the image as immutable. Fix a problem by building a new image, never by editing a running container.
    • Never bake secrets into a layer; a deleted file stays in an earlier layer.
    • Pin versions of the base image, and decide who updates them.
    • Plan for the orchestrator. The container will be killed and restarted by something else, so it must start fast and stop on a signal.

    Common mistakes

    • One big layer that rebuilds everything on every code change.
    • Shell-form ENTRYPOINT that swallows signals.
    • Running as root because nobody changed the default.
    • Floating tags such as latest, so two builds of the same Dockerfile differ.
    • No memory limit, or a heap sized as if the container were the whole machine.
    • Writing state inside the container, where it vanishes with it.

    Key takeaways

    • An image is an unchanging package; a container is an isolated process started from it.
    • Each Dockerfile instruction is a layer, and a changed layer rebuilds everything after it, so order by rate of change.
    • A Spring Boot layered jar splits libraries from application code so a code change rebuilds only a small layer; the lab shows this split on the jar, not on an image.
    • Use multi-stage builds, a non-root user, exec-form entry points and pinned base images.
    • Containers have no resource limits by default; set a memory limit and size the heap inside it.
    • Compose is a local convenience, not a production orchestrator.

    Practice exercises

    Exercise 1 (30 min). Rewrite the minimal Dockerfile so that dependency files are copied before source files. For a change to one source file, list which layers are rebuilt in the original and in your version.

    Exercise 2 (1 hour). Run the lab, then add a second dependency to its build.gradle.kts and predict which layer fingerprints change before you re-run. Restore the file afterwards.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments