Practice: containers basics
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Four mistakes cause most early Docker confusion: mixing up images and containers, choosing the wrong tool, misreading image names, and config code that crashes. Each has a short, reliable fix.
Mistake 1: treating an image and a container as the same thing
An image is a read-only template and a container is one run of it. Mixing them up is the first mistake. The model below starts two containers from one image.
Example 1 · One image, two containers
import java.util.ArrayList;import java.util.List;
// A simplified model: an image is read-only, each container adds its own writable layerrecord Image(String name, List<String> layers) {}
class Container { private final String name; private final Image image; private final List<String> writableLayer = new ArrayList<>();
Container(String name, Image image) { this.name = name; this.image = image; }
void writeFile(String file) { writableLayer.add(file); }
void show() { System.out.println(name + " (from " + image.name() + ")"); System.out.println(" read-only layers: " + image.layers()); System.out.println(" own files: " + writableLayer); }}
public class ImageVsContainerDemo { public static void main(String[] args) { Image jdk = new Image("eclipse-temurin:25-jdk", List.of("ubuntu", "jdk-25", "certificates"));
Container asha = new Container("asha-lab", jdk); Container ravi = new Container("ravi-lab", jdk); asha.writeFile("/app/Marks.class"); ravi.writeFile("/tmp/notes.txt");
asha.show(); ravi.show(); System.out.println("Image layers after both runs: " + jdk.layers()); }}asha-lab (from eclipse-temurin:25-jdk) read-only layers: [ubuntu, jdk-25, certificates] own files: [/app/Marks.class] ravi-lab (from eclipse-temurin:25-jdk) read-only layers: [ubuntu, jdk-25, certificates] own files: [/tmp/notes.txt] Image layers after both runs: [ubuntu, jdk-25, certificates]
What this code does
- A simplified model: both containers share the image's read-only layers, and each writes only into its own list (its writable layer).
- Asha's compiled class is not in Ravi's container, and the image's layers are unchanged after both runs.
An image is made of layers; a container has its own thin writable layer on top, so deleting a container never changes the image. The other words fit around them: a registry stores images (Docker Hub, GitHub Container Registry), a tag names one version, and the daemon (dockerd) is the background service that pulls images and runs containers.
Remember:
- Image = class, container = object: one image, many containers.
docker imageslists images;docker ps -alists containers.docker rmdeletes a container;docker rmideletes an image.
Mistake 2: picking a container where a VM is needed (or the reverse)
A container shares the host kernel, so it is fast and light. A VM boots its own full OS, so it is heavier but isolates more. The helper below turns the rule of thumb into code.
Example 2 · VM or container: a rule of thumb in code
import java.util.List;
record Need(String scenario, boolean otherKernel, boolean untrustedCode, boolean legacyOs) {}
public class VmOrContainerDemo { // A rule of thumb, not a law: containers by default, a VM when a container cannot do the job static String decide(Need n) { if (n.otherKernel()) return "VM (needs a different operating system kernel)"; if (n.legacyOs()) return "VM (old app tied to a full operating system)"; if (n.untrustedCode()) return "VM (strong isolation for code you do not trust)"; return "container (same Linux kernel, starts in seconds)"; }
public static void main(String[] args) { List<Need> needs = List.of( new Need("Run shoplite-api the same way on every laptop", false, false, false), new Need("Test a Windows-only billing app on a Linux server", true, false, false), new Need("Run 20 copies of a Java service on one server", false, false, false), new Need("Run strangers' code in an online judge", false, true, false), new Need("Keep a 2008 college ERP that needs its own old OS", false, false, true));
for (Need n : needs) { System.out.println(n.scenario() + " -> " + decide(n)); } }}Run shoplite-api the same way on every laptop -> container (same Linux kernel, starts in seconds) Test a Windows-only billing app on a Linux server -> VM (needs a different operating system kernel) Run 20 copies of a Java service on one server -> container (same Linux kernel, starts in seconds) Run strangers' code in an online judge -> VM (strong isolation for code you do not trust) Keep a 2008 college ERP that needs its own old OS -> VM (old app tied to a full operating system)
What this code does
- The checks go from hardest limits to softest: a different kernel always needs a VM; then old full-OS apps; then untrusted code.
- Everything else, such as your own Java services on Linux, defaults to containers.
- Real decisions also weigh cost and team skills; this is the first question to ask, not the only one.
Use containers for your own Linux services, and choose a VM when you need a different operating system, strong isolation for code you do not trust, or an old app tied to a full OS. Many companies run containers inside VMs and get both.
Mistake 3: unpinned and misread image names
A full image name is registry/namespace/repository:tag, and Docker fills in what you leave out. Misreading names leads to unpinned images. The program below decodes names.
Example 3 · Decoding image names
import java.util.List;
record ImageName(String registry, String path, String tag) {
// Docker's defaults: registry docker.io, namespace library (official images), tag latest static ImageName parse(String name) { String registry = "docker.io"; String rest = name; int slash = name.indexOf('/'); if (slash > 0) { String first = name.substring(0, slash); if (first.contains(".") || first.contains(":") || first.equals("localhost")) { registry = first; rest = name.substring(slash + 1); } } String tag = "latest"; int colon = rest.lastIndexOf(':'); if (colon > rest.lastIndexOf('/')) { tag = rest.substring(colon + 1); rest = rest.substring(0, colon); } if (registry.equals("docker.io") && !rest.contains("/")) { rest = "library/" + rest; } return new ImageName(registry, rest, tag); }
boolean pinned() { return !tag.equals("latest"); }}
public class ImageNameDemo { public static void main(String[] args) { List<String> names = List.of( "eclipse-temurin:25-jre", "mysql", "grafana/grafana:11.3.0", "ghcr.io/asha-rao/shoplite-api:1.2.0", "localhost:5000/shoplite-hello");
for (String name : names) { ImageName n = ImageName.parse(name); System.out.println(name); System.out.println(" registry=" + n.registry() + " path=" + n.path() + " tag=" + n.tag() + (n.pinned() ? "" : " <- not pinned")); } }}eclipse-temurin:25-jre registry=docker.io path=library/eclipse-temurin tag=25-jre mysql registry=docker.io path=library/mysql tag=latest <- not pinned grafana/grafana:11.3.0 registry=docker.io path=grafana/grafana tag=11.3.0 ghcr.io/asha-rao/shoplite-api:1.2.0 registry=ghcr.io path=asha-rao/shoplite-api tag=1.2.0 localhost:5000/shoplite-hello registry=localhost:5000 path=shoplite-hello tag=latest <- not pinned
What this code does
- The first part before
/is a registry only if it looks like a host: it has a.or:, or islocalhost. Sografanais a namespace on Docker Hub. - The tag is searched only after the last
/, which is whylocalhost:5000is not read as a tag. mysqlandlocalhost:5000/shoplite-hellofall back tolatest, so they are flagged as not pinned.
Docker fills in registry docker.io, namespace library for official images, and tag latest, so mysql really means docker.io/library/mysql:latest. An image is pinned when its name fixes the version: a tag such as mysql:8.4 or, strictest, a digest (@sha256:...). latest is not a version: it moves whenever the publisher pushes. A : before the first / belongs to the registry's port (localhost:5000/...), not to a tag.
8.4 can be re-pushed with patch updates. Teams that need the exact same bytes everywhere pin the digest.Mistake 4: a configuration loader that crashes instead of failing fast
Fail fast means stopping at start-up with a message that names the problem. The broken loader below crashes with a NullPointerException; the fixed one explains what is missing.
Example 4 · The loader that crashes with a NullPointerException
import java.util.Map;
record AppConfig(String env, String dbUrl, int port) {
static AppConfig from(Map<String, String> vars) { String env = vars.getOrDefault("APP_ENV", "dev"); String dbUrl = vars.get("DB_URL").trim(); // bug: get returns null when DB_URL is not set if (dbUrl.isEmpty()) { if (env.equals("prod")) { throw new IllegalStateException("DB_URL is required when APP_ENV=prod"); } dbUrl = "jdbc:mysql://localhost:3306/shoplite"; } int port = Integer.parseInt(vars.getOrDefault("PORT", "8080")); return new AppConfig(env, dbUrl, port); }}
public class BrokenConfigDemo { static void start(String label, Map<String, String> vars) { try { AppConfig c = AppConfig.from(vars); System.out.println(label + ": started with " + c.dbUrl() + " on port " + c.port()); } catch (RuntimeException e) { System.out.println(label + ": " + e.getClass().getSimpleName() + ": " + e.getMessage()); } }
public static void main(String[] args) { start("dev, nothing set", Map.of()); start("prod with DB_URL", Map.of("APP_ENV", "prod", "DB_URL", "jdbc:mysql://db.shoplite.in:3306/shoplite")); start("prod without DB_URL", Map.of("APP_ENV", "prod")); }}dev, nothing set: NullPointerException: Cannot invoke "String.trim()" because the return value of "java.util.Map.get(Object)" is null prod with DB_URL: started with jdbc:mysql://db.shoplite.in:3306/shoplite on port 8080 prod without DB_URL: NullPointerException: Cannot invoke "String.trim()" because the return value of "java.util.Map.get(Object)" is null
What this code does
vars.get("DB_URL")isnullwhen the variable is not set, so.trim()throws before theifcan use the default or the clear message.- The message names
String.trim()andMap.get, notDB_URL: the person reading the container log has to open the code to understand it. Map.of(...)stands in forSystem.getenv(), so you can test all three cases without changing real variables.
Example 5 · The fixed loader fails fast
import java.util.Map;
record AppConfig(String env, String dbUrl, int port) {
static AppConfig from(Map<String, String> vars) { String env = vars.getOrDefault("APP_ENV", "dev"); String dbUrl = vars.get("DB_URL"); if (dbUrl == null || dbUrl.isBlank()) { if (env.equals("prod")) { throw new IllegalStateException("DB_URL is required when APP_ENV=prod"); } dbUrl = "jdbc:mysql://localhost:3306/shoplite"; } int port = Integer.parseInt(vars.getOrDefault("PORT", "8080")); return new AppConfig(env, dbUrl, port); }}
public class FixedConfigDemo { static void start(String label, Map<String, String> vars) { try { AppConfig c = AppConfig.from(vars); System.out.println(label + ": started with " + c.dbUrl() + " on port " + c.port()); } catch (IllegalStateException e) { System.out.println(label + ": Startup failed: " + e.getMessage()); } }
public static void main(String[] args) { start("dev, nothing set", Map.of()); start("prod with DB_URL", Map.of("APP_ENV", "prod", "DB_URL", "jdbc:mysql://db.shoplite.in:3306/shoplite")); start("prod without DB_URL", Map.of("APP_ENV", "prod")); }}dev, nothing set: started with jdbc:mysql://localhost:3306/shoplite on port 8080 prod with DB_URL: started with jdbc:mysql://db.shoplite.in:3306/shoplite on port 8080 prod without DB_URL: Startup failed: DB_URL is required when APP_ENV=prod
What this code does
dbUrl == null || dbUrl.isBlank()checks before calling anything on the value;||stops at the first true test, soisBlank()never runs onnull.- Dev gets the local default, prod with
DB_URLstarts normally, and prod without it stops with a message that names the variable. - This is the same
AppConfig.fromas the module's first lesson; in the real programmainpassesSystem.getenv().
The fix checks for null (and blank) first, uses the default in dev, and throws IllegalStateException with a clear message in prod. Inside a container this matters even more: the only thing you see is the log, and the container exits with code 1.
Find the bug
Find the config bug
Click the faulty line.
Which line crashes when DB_URL is not set?
Round 1 of 2Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Match each term to its meaning. Write six lines in the form term: letter.
Terms: image, container, layer, registry, tag, daemon.
a) a server that stores and serves images
b) the background service that pulls images and runs containers
c) a read-only template for containers
d) a version label written after : in an image name
e) one read-only set of file changes inside an image
f) a running or stopped instance with its own writable layer
image: c container: f layer: e registry: a tag: d daemon: b
Exercise 2· Easy
VM or container? Decide for each scenario and give a one-line reason.
- Every intern needs the same MySQL 8.4 for ShopLite on their laptop.
- The college must keep running an exam app that only works on Windows Server 2012.
- A coding contest site runs code submitted by thousands of strangers.
- ShopLite needs 10 copies of
shoplite-apibehind a load balancer during the Diwali sale. - You want to try JDK 25 for an hour without installing it.
1. container 2. VM 3. VM (or a container inside a VM) 4. container 5. container
Exercise 3· Medium
Write the full name (registry/namespace/repository:tag) of each image, and mark the ones that are not pinned.
eclipse-temurin:25-jdkpostgresgrafana/loki:3.3.0ghcr.io/asha-rao/shoplite-api:1.2.0mysql:latest
1. docker.io/library/eclipse-temurin:25-jdk 2. docker.io/library/postgres:latest (not pinned) 3. docker.io/grafana/loki:3.3.0 4. ghcr.io/asha-rao/shoplite-api:1.2.0 5. docker.io/library/mysql:latest (not pinned)
Exercise 4· Medium
Write static boolean isPinned(String image): an image is pinned when it has a digest (@sha256:) or a tag other than latest after the last /. Print the result for mysql:8.4, mysql, eclipse-temurin:latest, localhost:5000/shoplite-hello and ghcr.io/asha-rao/shoplite-api:1.2.0, in that order, as in the expected output.
pinned mysql:8.4 NOT pinned mysql NOT pinned eclipse-temurin:latest NOT pinned localhost:5000/shoplite-hello pinned ghcr.io/asha-rao/shoplite-api:1.2.0
Exercise 5· Medium
This port reader crashes with a NumberFormatException when PORT is missing or wrong. Fix port so that a missing or blank PORT gives 8080, and a value that is not a number, or is outside 1 to 65535, throws IllegalStateException with the messages shown. Do not change start or main.
import java.util.Map;
public class PortConfigDemo { static int port(Map<String, String> vars) { return Integer.parseInt(vars.get("PORT")); // crashes when PORT is missing or not a number }
static void start(Map<String, String> vars) { try { System.out.println("PORT=" + vars.get("PORT") + " -> port " + port(vars)); } catch (IllegalStateException e) { System.out.println("PORT=" + vars.get("PORT") + " -> Startup failed: " + e.getMessage()); } }
public static void main(String[] args) { start(Map.of()); start(Map.of("PORT", "9090")); start(Map.of("PORT", "80a80")); start(Map.of("PORT", "70000")); }}PORT=null -> port 8080 PORT=9090 -> port 9090 PORT=80a80 -> Startup failed: PORT must be a number, got '80a80' PORT=70000 -> Startup failed: PORT must be between 1 and 65535, got 70000
Exercise 6· Medium
Write one docker run command for each task.
- Check that Docker works, and leave no container behind.
- Open JShell from JDK 25 to try a snippet, deleted when you exit.
- Run
Marks.javafrom your current folder with JDK 25, without installing a JDK.
docker run --rm hello-world docker run -it --rm eclipse-temurin:25-jdk jshell docker run --rm -v "$PWD":/app -w /app eclipse-temurin:25-jdk java Marks.java
Exercise 7· Hard
Build an image policy check. Reuse the ImageName.parse rules from the "Decoding image names" example (registry, path, tag with Docker's defaults). problems(image) returns a list: "tag is latest or missing" when the tag is latest, and "registry X is not allowed" when the registry is not docker.io or ghcr.io. Check the five images in the expected output, print OK or REJECT with the problems joined by ; , then the count.
OK eclipse-temurin:25-jre REJECT mysql (tag is latest or missing) OK ghcr.io/asha-rao/shoplite-api:1.2.0 REJECT quay.io/keycloak/keycloak:26.0 (registry quay.io is not allowed) REJECT registry.example.in/tools/backup:latest (tag is latest or missing; registry registry.example.in is not allowed) 3 of 5 images rejected
Exercise 8· Hard
ShopLite must fail fast with one message that lists every missing variable, not only the first. JWT_SECRET is always required; when APP_ENV is prod, DB_URL, DB_USER, DB_PASSWORD and CORS_ALLOWED_ORIGINS are required too. A blank value counts as missing. Write missing(Map<String, String> vars) and check(label, vars), and run the four cases from the expected output (pass Map.of(...) instead of real variables). Never print a value, only names.
dev with secret: OK dev, nothing set: Startup failed: missing JWT_SECRET prod, half set: Startup failed: missing JWT_SECRET, DB_PASSWORD, CORS_ALLOWED_ORIGINS prod, all set: OK
Interview questions
Questions interviewers ask on this topic.
Finish up
Mark complete & continue
Next: Project: make ShopLite environment-ready