Back to Docker: Images, Containers, Multi-Stage
Q3Question 3 of 12

What are Docker containers and how do they differ from virtual mach

Answer: A Docker container is a lightweight, isolated runtime environment that packages an application with all its dependencies so it runs consistently on any machine, using the host OS kernel instead of a full operating system like a virtual machine.

Key Concepts
  • A Docker container is a lightweight, isolated process that shares the host OS kernel and runs from a read-only image with a writable layer on top.
  • Containers start in seconds and use megabytes of RAM, while virtual machines start in minutes and use gigabytes.
  • A Dockerfile defines how to build an image, layer by layer, from a base image through dependency installation to the final application.
  • Multi-stage builds reduce image size by compiling in one stage and copying only the JAR to a minimal runtime stage.
  • Docker images are immutable and versioned with tags, ensuring the same image runs identically in dev, staging, and production.
  • Containers communicate through Docker networks and persist data through volumes.
  • A non-root user inside the container is a security best practice for banking applications.

Definition

A Docker container is a lightweight, isolated runtime environment that packages an application with all its dependencies so it runs consistently on any machine, using the host OS kernel instead of a full operating system like a virtual machine.
  • Docker image is a read-only template with layers containing the OS base, runtime (JDK), dependencies, and application code.
  • Docker container is a running instance of an image with its own filesystem, network, and process space, isolated from other containers.
  • Dockerfile is a text file with instructions (FROM, COPY, RUN, CMD) that Docker uses to build an image layer by layer.
  • Docker Hub is a public registry where you push and pull images, similar to Maven Central for JARs.
  • Container vs VM: a container shares the host kernel and runs as an isolated process; a VM runs a full guest OS with its own kernel.

Think of the National Bank of India deploying software across branches. A virtual machine is like shipping a full computer to each branch: operating system, drivers, JDK, application. A container is like shipping a sealed box with just the application and its runtime. Every branch already has a standard desk (the host OS kernel). The sealed box opens on any desk and runs the same way. The box is smaller, starts faster, and you can fit many boxes on one desk.

Understanding the Concepts

What is a Docker container?

A Docker container is an isolated process running on the host operating system. It has its own filesystem (from the image), its own network interface, and its own process ID namespace. But it shares the host kernel, which makes it far lighter than a virtual machine.

When you run docker run, Docker creates a container from an image, assigns it a writable layer on top of the read-only image layers, starts the process defined in the CMD instruction, and isolates it using Linux namespaces and cgroups.

BASH
# Pull a Java runtime image
docker pull eclipse-temurin:21-jre-alpine

# Run a container from the image
docker run --rm eclipse-temurin:21-jre-alpine java -version
TEXT
openjdk version "21.0.4" 2024-07-16 LTS
OpenJDK Runtime Environment Temurin-21.0.4+7 (build 21.0.4+7-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.4+7 (build 21.0.4+7-LTS, mixed mode)
JAVA
package com.bank.docker;

public class ContainerInfoDemo {

    public static void main(String[] args) {
        System.out.println("Running inside a container:");
        System.out.println("  Java version: " + System.getProperty("java.version"));
        System.out.println("  OS: " + System.getProperty("os.name"));
        System.out.println("  Arch: " + System.getProperty("os.arch"));
        System.out.println("  Available processors: "
            + Runtime.getRuntime().availableProcessors());
        System.out.println("  Max memory: "
            + Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
        System.out.println("  User: " + System.getProperty("user.name"));
    }
}
TEXT
Running inside a container:
  Java version: 21.0.4
  OS: Linux
  Arch: aarch64
  Available processors: 4
  Max memory: 512 MB
  User: bankapp

How are containers different from virtual machines?

AspectContainerVirtual Machine
KernelShares host kernelHas its own kernel
SizeMegabytes (50-300 MB)Gigabytes (2-10 GB)
Startup timeSeconds (1-5s)Minutes (30-120s)
IsolationProcess-level (namespaces, cgroups)Hardware-level (hypervisor)
Resource overheadLow (5-10% CPU)High (15-30% CPU)
Density100+ containers per host10-20 VMs per host
SecurityWeaker isolation (shared kernel)Stronger isolation (separate kernel)
Use caseMicroservices, CI/CDLegacy apps, multi-tenant isolation
PortabilityImage runs on any Docker hostVM image is hypervisor-specific
JAVA
package com.bank.docker;

public class ContainerVsVMDemo {
    public static void main(String[] args) {
        System.out.println("=== Container ===");
        System.out.println("Image size: ~150 MB (JRE Alpine + banking app)");
        System.out.println("Startup: 3 seconds");
        System.out.println("Memory: 256 MB for the JVM");
        System.out.println("Isolation: Linux namespaces (PID, NET, MNT)");
        System.out.println();

        System.out.println("=== Virtual Machine ===");
        System.out.println("Image size: ~5 GB (full Ubuntu + JDK + banking app)");
        System.out.println("Startup: 60 seconds");
        System.out.println("Memory: 2 GB for the guest OS + JVM");
        System.out.println("Isolation: Hypervisor (full kernel separation)");
    }
}
TEXT
=== Container ===
Image size: ~150 MB (JRE Alpine + banking app)
Startup: 3 seconds
Memory: 256 MB for the JVM
Isolation: Linux namespaces (PID, NET, MNT)

=== Virtual Machine ===
Image size: ~5 GB (full Ubuntu + JDK + banking app)
Startup: 60 seconds
Memory: 2 GB for the guest OS + JVM
Isolation: Hypervisor (full kernel separation)

How do you write a Dockerfile for a Spring Boot banking application?

A Dockerfile describes how to build an image. Each instruction creates a layer. Docker caches layers, so unchanged layers are not rebuilt.

DOCKERFILE
# ---- Build stage ----
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app

# Copy build files first (cached if unchanged)
COPY pom.xml mvnw ./
COPY .mvn .mvn
RUN ./mvnw dependency:go-offline -B

# Copy source and build
COPY src src
RUN ./mvnw package -DskipTests -B

# ---- Runtime stage ----
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app

# Security: run as non-root user
RUN addgroup -S bankgroup && adduser -S bankapp -G bankgroup
USER bankapp

# Copy only the JAR from the build stage
COPY --from=builder /app/target/transfer-service-1.0.0.jar app.jar

# JVM tuning for containers
ENV JAVA_OPTS="-XX:MaxRAMPercentage=75.0 -XX:+UseG1GC"

EXPOSE 8080
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
BASH
# Build the image
docker build -t national-bank/transfer-service:1.0.0 .

# Run the container
docker run -d \
  --name transfer-service \
  -p 8080:8080 \
  -e SPRING_PROFILES_ACTIVE=production \
  -e DB_URL=jdbc:postgresql://db:5432/bankdb \
  --memory=512m \
  national-bank/transfer-service:1.0.0

# Check it is running
docker ps
TEXT
CONTAINER ID  IMAGE                                    STATUS         PORTS
a1b2c3d4e5f6  national-bank/transfer-service:1.0.0     Up 5 seconds   0.0.0.0:8080->8080/tcp
JAVA
package com.bank.docker;

public class DockerfileExplainedDemo {
    public static void main(String[] args) {
        System.out.println("Multi-stage Dockerfile layers:");
        System.out.println("Stage 1 (builder):");
        System.out.println("  Layer 1: eclipse-temurin:21-jdk-alpine (base)");
        System.out.println("  Layer 2: pom.xml + mvnw (build config)");
        System.out.println("  Layer 3: dependency:go-offline (cached deps)");
        System.out.println("  Layer 4: src/ (application source)");
        System.out.println("  Layer 5: mvnw package (compile + package)");
        System.out.println();
        System.out.println("Stage 2 (runtime):");
        System.out.println("  Layer 1: eclipse-temurin:21-jre-alpine (smaller base)");
        System.out.println("  Layer 2: non-root user (security)");
        System.out.println("  Layer 3: app.jar from builder (final app)");
        System.out.println();
        System.out.println("Result: ~150 MB image instead of ~500 MB");
    }
}
TEXT
Multi-stage Dockerfile layers:
Stage 1 (builder):
  Layer 1: eclipse-temurin:21-jdk-alpine (base)
  Layer 2: pom.xml + mvnw (build config)
  Layer 3: dependency:go-offline (cached deps)
  Layer 4: src/ (application source)
  Layer 5: mvnw package (compile + package)

Stage 2 (runtime):
  Layer 1: eclipse-temurin:21-jre-alpine (smaller base)
  Layer 2: non-root user (security)
  Layer 3: app.jar from builder (final app)

Result: ~150 MB image instead of ~500 MB

What are Docker images and layers?

A Docker image is a stack of read-only layers. Each Dockerfile instruction creates a layer. When you pull an image, Docker downloads only the layers you do not already have. When you build, Docker caches layers and reuses them if the instruction and its inputs have not changed.

BASH
# View image layers
docker history national-bank/transfer-service:1.0.0

# View image size
docker images national-bank/transfer-service
TEXT
REPOSITORY                            TAG     SIZE
national-bank/transfer-service        1.0.0   148MB
JAVA
package com.bank.docker;

public class ImageLayersDemo {
    public static void main(String[] args) {
        System.out.println("Image layer caching:");
        System.out.println();
        System.out.println("First build (no cache): 2 minutes");
        System.out.println("  - Downloads JDK base image");
        System.out.println("  - Downloads all Maven dependencies");
        System.out.println("  - Compiles application");
        System.out.println();
        System.out.println("Second build (only code changed): 15 seconds");
        System.out.println("  - CACHED: JDK base image");
        System.out.println("  - CACHED: Maven dependencies");
        System.out.println("  - REBUILT: compile (only src changed)");
        System.out.println();
        System.out.println("Key: put rarely-changing layers (deps) before");
        System.out.println("frequently-changing layers (src) in Dockerfile");
    }
}
TEXT
Image layer caching:

First build (no cache): 2 minutes
  - Downloads JDK base image
  - Downloads all Maven dependencies
  - Compiles application

Second build (only code changed): 15 seconds
  - CACHED: JDK base image
  - CACHED: Maven dependencies
  - REBUILT: compile (only src changed)

Key: put rarely-changing layers (deps) before
frequently-changing layers (src) in Dockerfile

What are common mistakes with Docker?

Mistake 1: Using the JDK in the runtime image

Wrong: the runtime image includes the full JDK with compiler and tools. The image is 400+ MB.

DOCKERFILE
# WRONG: JDK in production image
FROM eclipse-temurin:21-jdk-alpine
COPY target/app.jar app.jar
CMD ["java", "-jar", "app.jar"]
# Image size: ~400 MB

Correct: use multi-stage build with JRE-only in the runtime stage.

DOCKERFILE
# CORRECT: JDK only in build stage, JRE in runtime
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app
COPY . .
RUN ./mvnw package -DskipTests

FROM eclipse-temurin:21-jre-alpine
COPY --from=builder /app/target/app.jar app.jar
CMD ["java", "-jar", "app.jar"]
# Image size: ~150 MB

Mistake 2: Running as root inside the container

Wrong: the application runs as root, which is a security risk in banking environments.

DOCKERFILE
# WRONG: runs as root by default
FROM eclipse-temurin:21-jre-alpine
COPY app.jar app.jar
CMD ["java", "-jar", "app.jar"]

Correct: create a non-root user and switch to it.

DOCKERFILE
# CORRECT: non-root user
FROM eclipse-temurin:21-jre-alpine
RUN addgroup -S bankgroup && adduser -S bankapp -G bankgroup
USER bankapp
COPY app.jar app.jar
CMD ["java", "-jar", "app.jar"]

How do you manage container networking and volumes?

Containers communicate through Docker networks. Data persists through volumes.

BASH
# Create a network for the banking services
docker network create bank-network

# Run PostgreSQL with a volume for data persistence
docker run -d \
  --name bank-db \
  --network bank-network \
  -v bank-data:/var/lib/postgresql/data \
  -e POSTGRES_DB=bankdb \
  -e POSTGRES_USER=bankadmin \
  -e POSTGRES_PASSWORD=secretpass \
  postgres:16-alpine

# Run the transfer service on the same network
docker run -d \
  --name transfer-service \
  --network bank-network \
  -p 8080:8080 \
  -e DB_URL=jdbc:postgresql://bank-db:5432/bankdb \
  national-bank/transfer-service:1.0.0
JAVA
package com.bank.docker;

public class NetworkingDemo {
    public static void main(String[] args) {
        System.out.println("Docker networking for banking services:");
        System.out.println();
        System.out.println("Network: bank-network (bridge)");
        System.out.println("  bank-db:5432        -> PostgreSQL");
        System.out.println("  transfer-service:8080 -> Spring Boot app");
        System.out.println("  redis-cache:6379     -> Redis session store");
        System.out.println();
        System.out.println("Volumes:");
        System.out.println("  bank-data -> /var/lib/postgresql/data (persistent)");
        System.out.println("  bank-logs -> /var/log/bank (log files)");
        System.out.println();
        System.out.println("Containers on the same network can reach each");
        System.out.println("other by container name (Docker DNS resolution).");
    }
}
TEXT
Docker networking for banking services:

Network: bank-network (bridge)
  bank-db:5432        -> PostgreSQL
  transfer-service:8080 -> Spring Boot app
  redis-cache:6379     -> Redis session store

Volumes:
  bank-data -> /var/lib/postgresql/data (persistent)
  bank-logs -> /var/log/bank (log files)

Containers on the same network can reach each
other by container name (Docker DNS resolution).

What should a senior engineer know?

- JVM container awareness. Since Java 10, the JVM detects container memory and CPU limits automatically. Use -XX:MaxRAMPercentage=75.0 instead of -Xmx so the heap scales with the container's memory limit. The remaining 25% is for metaspace, thread stacks, and native memory.

- Distroless images. Google's distroless images contain only the runtime and no shell. This reduces the attack surface: an attacker who compromises the container cannot run bash. For banking services, this is a strong security posture.

- Image scanning. Tools like Trivy, Grype, and Snyk scan images for known vulnerabilities in base OS packages and application dependencies. Banking regulators require evidence that production images are vulnerability-free.

- BuildKit and layer caching. Docker BuildKit supports mount caches for Maven/Gradle repositories, reducing build times from minutes to seconds for dependency-heavy Java projects.

- Health checks. Define a HEALTHCHECK instruction in the Dockerfile so Docker (and Kubernetes) can detect when the application is not responding and restart it automatically.

What are common interview follow-up questions?

  • What is the difference between CMD and ENTRYPOINT in a Dockerfile?
  • How do you reduce Docker image size for a Java application?
  • What are the security best practices for running containers in production?
  • How does Docker networking work, and what is a bridge network?
  • What is the difference between a bind mount and a named volume?

Visual Overview

DIAGRAM
  Container vs Virtual Machine
  =============================

  Container                         Virtual Machine
  ─────────                         ───────────────
  ┌────────────────────────┐        ┌────────────────────────┐
  │ App  │ App  │ App      │        │ App  │ App  │ App      │
  │      │      │          │        │      │      │          │
  ├──────┴──────┴──────────┤        ├──────┴──────┴──────────┤
  │     Container Runtime  │        │  Guest OS │ Guest OS   │
  │     (Docker Engine)    │        │  (Ubuntu) │ (CentOS)   │
  ├────────────────────────┤        ├───────────┴────────────┤
  │     Host OS Kernel     │        │     Hypervisor         │
  ├────────────────────────┤        ├────────────────────────┤
  │     Hardware           │        │     Hardware           │
  └────────────────────────┘        └────────────────────────┘
  Shares kernel, lightweight        Each VM has full kernel


  Multi-Stage Dockerfile
  =======================

  Stage 1 (builder)              Stage 2 (runtime)
  ─────────────────              ─────────────────
  JDK + Maven                    JRE only
  ┌──────────────┐               ┌──────────────┐
  │ pom.xml      │               │ app.jar      │
  │ src/         │  ──COPY──>    │ (from stage1)│
  │ dependencies │               │              │
  │ compile      │               │ non-root user│
  │ package      │               │              │
  │ app.jar      │               │ EXPOSE 8080  │
  └──────────────┘               └──────────────┘
  ~500 MB (discarded)            ~150 MB (shipped)

Key Takeaway

Docker containers changed how banking applications are deployed. Instead of installing Java, configuring the OS, and hoping the production environment matches development, you build an image once and run it anywhere. The image includes the JRE, the application JAR, and all configuration. What runs on your laptop runs on staging runs on production.

The key difference from virtual machines is weight. A container shares the host kernel and starts in seconds. A VM boots an entire operating system and takes minutes. You can run a hundred containers on a machine that would handle twenty VMs. For a banking platform with dozens of microservices, this density matters.

Multi-stage builds are essential for Java. The build stage uses the full JDK to compile and package. The runtime stage uses a minimal JRE image. This cuts the image from 500 MB to 150 MB, which means faster pulls, faster deployments, and a smaller attack surface. Always run as a non-root user inside the container, especially in financial systems where security audits check for this.

The JVM is container-aware since Java 10. It reads the memory limit from cgroups and sets the heap accordingly. Use -XX:MaxRAMPercentage=75.0 to give the heap three-quarters of the container's memory and leave the rest for metaspace and native memory.

One sentence to remember: a Docker container packages your application with its runtime into a lightweight, portable, immutable unit that starts in seconds and runs the same everywhere.

---

Share
Use ← → arrow keys to navigate