Docker for Kubernetes · Lesson 2 · About 25 minutes
Your first Dockerfile: a Java service in an image
By the end, you will have built an image of your own Java service, run two copies of it, and know which Dockerfile lines run during the build and which run when a container starts.
Warm-up from Lesson 1
Two questions from last time, from memory. Spacing the recall out like this is what moves it into long-term memory.
The service you'll package
A small HTTP service using only the JDK, so there are no dependencies to install. It listens on port 8080 and replies with its hostname. Inside a container, the hostname is the container ID, so you'll be able to tell copies apart.
import com.sun.net.httpserver.HttpServer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class App {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", exchange -> {
String host = InetAddress.getLocalHost().getHostName();
byte[] body = ("Hello from " + host + "\n").getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
System.out.println("Listening on port 8080");
}
}
Six instructions are enough
A Dockerfile is "a text-based document that's used to create a container image" (Docker Docs: Writing a Dockerfile). Docker reads it top to bottom. Each instruction either changes files, and so adds a layer (Lesson 1), or records a setting in the image.
| Instruction | What it does | Happens at |
|---|---|---|
FROM image | The base image you build on. Must come first. | Build |
WORKDIR /path | Sets the folder that later instructions and the container use. Creates it if it doesn't exist. | Build |
COPY src dest | Copies files from the build context (your folder) into the image. | Build |
RUN command | Runs a command and saves the resulting files as a new layer. | Build |
EXPOSE 8080 | Records which port the app listens on. It doesn't open anything. | Recorded only |
CMD ["java", "App"] | The default command for containers made from this image. Nothing runs at build time. | Run |
Sources: Dockerfile reference for each instruction.
CMD doesn't execute anything at build time, but specifies the intended command for the image." Compiling is a build job, so it goes in RUN. Starting the server is a run job, so it goes in CMD. Only one CMD counts, and yours replaces the base image's default (Temurin's is jshell).
Dockerfile reference: CMD
docker build -t dk-hello:0.1 ., the final . is the build context, "the set of files that your build can access." COPY paths are relative to it. -t names and tags the result.
Docker Docs: Build context
CMD java App (shell form) actually runs /bin/sh -c "java App". Then the shell is PID 1, and your program "will not receive Unix signals." CMD ["java", "App"] (exec form) makes Java PID 1 itself. You'll see the difference in the lab.
Dockerfile reference: shell and exec form
-p publishes it.
"The EXPOSE instruction doesn't actually publish the port." To reach the service from your Mac, run with -p 8080:8080 (your Mac's port : the container's port). Lesson 5 goes deeper into networking.
Dockerfile reference: EXPOSE
Write it yourself
Write the Dockerfile from these requirements, without scrolling back to the table if you can. Press Check (or ⌘/Ctrl+Enter) as often as you like; you get one hint at a time. Your draft is saved in this browser.
Build and run it on your machine
Make a new empty folder outside any git repo, for example docker-lab, and work in it. Create App.java from the code above (or paste the block below), then save your checked Dockerfile there as Dockerfile.
mkdir docker-lab && cd docker-lab
# create App.java and Dockerfile here, then:
ls # App.java Dockerfile
docker build -t dk-hello:0.1 . # the first build pulls eclipse-temurin:21-jdk
docker images dk-hello # about 500 MB. Lesson 3 cuts it down.
Run two copies from the one image. Same container port, different ports on your Mac:
docker run -d --name dk-hello -p 8080:8080 dk-hello:0.1
docker run -d --name dk-hello2 -p 8081:8080 dk-hello:0.1
curl localhost:8080 # Hello from 193ed5a3882e
curl localhost:8081 # Hello from b15b9c16cde1 (a different container)
docker logs dk-hello # Listening on port 8080
docker history dk-hello:0.1 # your instructions on top, the base image's below
Experiment: why exec form matters
Predict first: in Lesson 1, docker stop on sleep took 10 seconds. How long will it take for your Java service?
time docker stop dk-hello # under a second
docker ps -a --filter name=dk-hello # Exited (143)
Now break it. Change the last line of your Dockerfile to the shell form CMD java App, then:
docker build -t dk-hello:shell .
docker run -d --name dk-shell dk-hello:shell
docker top dk-shell # two processes: /bin/sh -c java App, then java App
time docker stop dk-shell # about 10 seconds
docker ps -a --filter name=dk-shell # Exited (137)
Exit code 143 is 128 + 15 (SIGTERM): Java received the signal and shut down. 137 is 128 + 9 (SIGKILL): the shell, as PID 1, ignored SIGTERM, and Docker killed everything when the 10-second grace period ran out (docker stop). Put CMD ["java", "App"] back afterwards.
docker rm -f dk-hello dk-hello2 dk-shell
docker rmi dk-hello:shell # keep dk-hello:0.1 for Lesson 3
- name your image in the Pod spec, as in
image: dk-hello:0.1. Without a tag it assumeslatest(Kubernetes: Images), so always give one. - run your CMD unless the Pod overrides it: "The
commandfield corresponds toENTRYPOINT, and theargsfield corresponds toCMD" (Kubernetes: Define a command). - stop a container exactly like your experiment did: TERM "to process 1 inside each container," then
SIGKILLafter a grace period that "defaults to 30 seconds" (Kubernetes: Pod termination). With shell form, every rollout would wait 30 seconds per Pod and then kill your app mid-request.
Check yourself
From memory, without scrolling up.
Keep going
Read next: Docker's Writing a Dockerfile (short, with a video), then the CMD and shell and exec form sections of the Dockerfile reference.
Keep for review: the new Dockerfile cheat sheet, the Docker CLI cheat sheet (now with build) and the glossary.
Ask your teacher: anything unclear is worth asking about in the chat, however small. When you finish, send both quiz scores, which questions you missed, and whether the build and the stop experiment worked on your machine.