Writing a Dockerfile line by line
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite runs only on your laptop: a friend with another Java version cannot start it. One short text file can describe the program and everything it needs, so it runs the same way on every computer.
The smallest Dockerfile: FROM, WORKDIR, COPY, EXPOSE, CMD
A Dockerfile is a plain text file, named exactly Dockerfile, that lists the steps Docker follows to build an image: which image to start from, which files to copy in and which command to run.
Each line starts with an instruction in capitals, followed by its arguments. This smallest Dockerfile packages one Java file.
FROM eclipse-temurin:25-jdkWORKDIR /appCOPY HealthServer.java .EXPOSE 8080CMD ["java", "HealthServer.java"]Example 1 · HealthServer.java: the program the image runs
Runs in: a terminal (stop it with Ctrl+C)
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.nio.charset.StandardCharsets;
public class HealthServer { public static void main(String[] args) throws IOException { int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080")); HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0); server.createContext("/health", exchange -> { byte[] body = "{\"status\":\"UP\"}".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); System.out.println("HealthServer listening on 0.0.0.0:" + port); }}HealthServer listening on 0.0.0.0:8080
What this code does
- It binds to
0.0.0.0, every network address, so requests that Docker forwards into the container reach it. Binding tolocalhostwould only accept requests from inside the container. - The port comes from the
PORTenvironment variable with 8080 as the default, matchingEXPOSE 8080in the Dockerfile. - The program never ends on its own. A container lives exactly as long as its main process, so the container keeps running until you stop it.
Example 2 · Check the program before you package it
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
public class HealthCheckDemo { public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/health", exchange -> { byte[] body = "{\"status\":\"UP\"}".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); int port = server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/health")).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("GET /health -> " + response.statusCode() + " " + response.body());
server.stop(0); System.out.println("Server stopped"); }}GET /health -> 200 {"status":"UP"}
Server stoppedWhat this code does
- The same
/healthhandler starts on a free port (0means "any free port"), so this test never clashes with something already on 8080. HttpClientcalls the endpoint once and prints the status and body, thenserver.stop(0)ends the program. Test a program like this before you put it in an image: a broken program in a container is still broken.
Dockerfile and HealthServer.java. Docker looks for the file named Dockerfile in the folder you build from.Build time vs run time: layers and metadata
A layer is a saved set of file changes stacked on top of the layers below it. FROM, WORKDIR, COPY and RUN make layers; EXPOSE and CMD only write metadata, which is image settings with no files.
Every instruction belongs to build time or run time. The picture shows which ones make a layer, and docker history lists them one row each.
Example 3 · docker history: one row per instruction
Runs in: a terminal with Docker installed
docker history shoplite-hello:0.1IMAGE CREATED CREATED BY SIZE COMMENT
5c0e8a3f91d2 2 minutes ago CMD ["java" "HealthServer.java"] 0B buildkit.dockerfile.v0
<missing> 2 minutes ago EXPOSE map[8080/tcp:{}] 0B buildkit.dockerfile.v0
<missing> 2 minutes ago COPY HealthServer.java . # buildkit 951B buildkit.dockerfile.v0
<missing> 2 minutes ago WORKDIR /app 0B buildkit.dockerfile.v0
<missing> 3 weeks ago CMD ["jshell"] 0B buildkit.dockerfile.v0
<missing> 3 weeks ago ENTRYPOINT ["/__cacert_entrypoint.sh"] 0B buildkit.dockerfile.v0
<missing> 3 weeks ago RUN /bin/sh -c set -eux; ARCH="$(dpkg --… 285MB buildkit.dockerfile.v0
<missing> 3 weeks ago ENV JAVA_HOME=/opt/java/openjdk 0B buildkit.dockerfile.v0
<missing> 4 weeks ago /bin/sh -c #(nop) ADD file:6f1d2c… in / 78.1MBWhat this code does
- Read from the bottom up: the base image rows come first, then your four instructions.
COPYadded 951 bytes (the source file);WORKDIR,EXPOSEandCMDshow0Bbecause they add no files that matter. - The base image has its own
ENTRYPOINT(a small script that then runs your command) andCMD ["jshell"]. YourCMDreplaces the baseCMD; that is why the container runsHealthServerand notjshell. - Dates, IDs and the base image rows will differ on your computer; the shape of the table stays the same.
Build time is when docker build reads the Dockerfile and makes the image. Run time is later, each time docker run starts a container from that image.
FROM(build time): picks the base image; its layers become the bottom of yours.RUN(build time): runs a command during the build, for exampleRUN javac Hello.java.EXPOSEandCMD(metadata): stored at build time, used at run time.CMDonly runs when a container starts.EXPOSEdocuments the port; it does not publish it. You still need-p 8080:8080ondocker run.
CMD vs ENTRYPOINT, exec form vs shell form
Exec form is the JSON-list way to write CMD or ENTRYPOINT, like ["java", "-jar", "app.jar"]. Docker starts the program directly, so it becomes PID 1, the first process in the container, and it receives the stop signal.
CMD and ENTRYPOINT both say what a container runs. The program below models how each one combines with the words you type after the image name.
Example 4 · How CMD, ENTRYPOINT and docker run arguments combine
import java.util.ArrayList;import java.util.List;
class ImageConfig { private final List<String> entrypoint; private final List<String> cmd;
ImageConfig(List<String> entrypoint, List<String> cmd) { this.entrypoint = entrypoint; this.cmd = cmd; }
// Docker runs: ENTRYPOINT + (the docker run arguments, or CMD when there are none) List<String> processFor(List<String> runArgs) { List<String> process = new ArrayList<>(entrypoint); process.addAll(runArgs.isEmpty() ? cmd : runArgs); return process; }}
public class CommandLineDemo { static void show(String label, ImageConfig image, List<String> runArgs) { List<String> process = image.processFor(runArgs); System.out.println(label); System.out.println(" runs : " + process); System.out.println(" PID 1: " + process.get(0)); }
public static void main(String[] args) { ImageConfig cmdOnly = new ImageConfig( List.of(), List.of("java", "HealthServer.java")); show("CMD only, docker run shoplite-hello:0.1", cmdOnly, List.of()); show("CMD only, docker run shoplite-hello:0.1 java -version", cmdOnly, List.of("java", "-version"));
ImageConfig both = new ImageConfig( List.of("java", "-jar", "/app/app.jar"), List.of("--server.port=8080")); show("ENTRYPOINT + CMD, no extra arguments", both, List.of()); show("ENTRYPOINT + CMD, extra argument --server.port=9090", both, List.of("--server.port=9090"));
ImageConfig shellForm = new ImageConfig( List.of(), List.of("/bin/sh", "-c", "java HealthServer.java")); show("CMD java HealthServer.java (shell form)", shellForm, List.of()); }}CMD only, docker run shoplite-hello:0.1 runs : [java, HealthServer.java] PID 1: java CMD only, docker run shoplite-hello:0.1 java -version runs : [java, -version] PID 1: java ENTRYPOINT + CMD, no extra arguments runs : [java, -jar, /app/app.jar, --server.port=8080] PID 1: java ENTRYPOINT + CMD, extra argument --server.port=9090 runs : [java, -jar, /app/app.jar, --server.port=9090] PID 1: java CMD java HealthServer.java (shell form) runs : [/bin/sh, -c, java HealthServer.java] PID 1: /bin/sh
What this code does
- This is a simplified model of Docker's rule in plain Java: the process is ENTRYPOINT plus either the
docker runarguments or, when there are none, CMD. It ignores the base image's own ENTRYPOINT script, which hands over to your command. - With only
CMD,docker run shoplite-hello:0.1 java -versionthrows the default away. WithENTRYPOINT, extra words such as--server.port=9090become arguments tojava -jar /app/app.jar. - The shell form line shows why it is risky: the first word of the process, PID 1, is
/bin/sh, notjava.
CMD sets the default command: any words after the image name in docker run replace it. ENTRYPOINT sets the fixed part: those words are added after it, and CMD becomes the default extra arguments.
Shell form is plain text, CMD java HealthServer.java. Docker stores it as /bin/sh -c "java HealthServer.java", so a shell can be PID 1. docker stop sends the SIGTERM signal (a polite "please stop") to PID 1 only, and a shell usually does not pass it on. Docker then waits 10 seconds and kills the container with SIGKILL. Use exec form for both instructions.
Predict the output
What does this container run?
Read the Dockerfile and the docker run line, then pick the command that starts.
Round 1 of 3
ENTRYPOINT fixes the program; CMD gives a default argument.
CMD ['java', '-jar', '/app/app.jar'] is not valid JSON, so Docker quietly treats the whole line as shell form and the container fails with [java,: not found.docker build: making the image
The build context is the folder you give to docker build (the final .). Docker sends it to the builder, and COPY can only use files that are inside it.
docker build turns the Dockerfile into an image. The commands below build shoplite-hello:0.1 (-t sets name and tag), run it with port 8080 published and call it.
Example 5 · Build, run and call shoplite-hello:0.1
Runs in: a terminal with Docker installed
# In the folder that holds Dockerfile and HealthServer.javadocker build -t shoplite-hello:0.1 .docker run --rm -p 8080:8080 shoplite-hello:0.1# In a second terminalcurl http://localhost:8080/health[+] Building 14.2s (8/8) FINISHED docker:desktop-linux
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 112B 0.0s
=> [internal] load metadata for docker.io/library/eclipse-temurin:25-jdk 1.9s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [1/3] FROM docker.io/library/eclipse-temurin:25-jdk@sha256:9b1e…c4d2 11.6s
=> => resolve docker.io/library/eclipse-temurin:25-jdk@sha256:9b1e…c4d2 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 1.06kB 0.0s
=> [2/3] WORKDIR /app 0.2s
=> [3/3] COPY HealthServer.java . 0.0s
=> exporting to image 0.3s
=> => exporting layers 0.1s
=> => writing image sha256:5c0e8a3f91d2… 0.0s
=> => naming to docker.io/library/shoplite-hello:0.1 0.0s
HealthServer listening on 0.0.0.0:8080
{"status":"UP"}What this code does
- The
FROMstep took longest because Docker downloaded the base image the first time.transferring context: 1.06kBis the build context: just the Dockerfile andHealthServer.java. writing imageandnaming to ...shoplite-hello:0.1mean the image is ready. Times, the digest aftersha256:and the builder name (docker:desktop-linuxon Docker Desktop) differ on every machine.- The last two lines are the container log and the
curlreply. On Windows PowerShell, usecurl.exeso you get the real curl and not the PowerShell alias.
Read the build output from the top. Docker loads the Dockerfile, looks up the base image, sends the build context and runs your steps as [1/3], [2/3], [3/3]. Only FROM, WORKDIR and COPY are numbered, because EXPOSE and CMD are metadata written in the final export step.
Run the same build again without changes and every step shows CACHED: the build finishes in about a second. The Layer caching lesson in this module explains exactly when Docker reuses a step.
Order of execution
From source file to a running container
Tap the steps in the order you do them.
Step 1/5 : lines from the legacy builder; the instructions behave the same.Packaging the Spring Boot fat jar
A fat jar (Spring Boot calls it an executable jar) is one file that holds your compiled classes plus every library they need, so java -jar app.jar alone starts the application.
./mvnw package writes the ShopLite jar to target/. This Dockerfile copies it into a small Java runtime image and starts it.
FROM eclipse-temurin:25-jreWORKDIR /appCOPY target/*.jar app.jarEXPOSE 8080ENTRYPOINT ["java", "-jar", "/app/app.jar"]Example 6 · shoplite-api:1.2.0 from the fat jar
Runs in: a Spring Boot project folder with Docker installed and the MySQL container from the Docker Essentials module running
./mvnw -B package -DskipTestsdocker build -t shoplite-api:1.2.0 .docker run --rm --name shoplite-api -p 8080:8080 \ --env-file .env \ -e DB_URL=jdbc:mysql://host.docker.internal:3307/shoplite \ shoplite-api:1.2.0# In a second terminalcurl http://localhost:8080/actuator/health => [3/3] COPY target/*.jar app.jar 0.4s
=> => naming to docker.io/library/shoplite-api:1.2.0 0.0s
2026-10-16T05:12:40.118Z INFO 1 --- [shoplite-api] [ main] com.shoplite.ShopLiteApplication : Starting ShopLiteApplication v1.2.0 using Java 25.0.4 with PID 1 (/app/app.jar started by root in /app)
2026-10-16T05:12:44.902Z INFO 1 --- [shoplite-api] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
2026-10-16T05:12:44.931Z INFO 1 --- [shoplite-api] [ main] com.shoplite.ShopLiteApplication : Started ShopLiteApplication in 5.423 seconds (process running for 6.107)
{"status":"UP"}What this code does
- Inside a container,
localhostmeans the container itself, soDB_URLpoints athost.docker.internal, Docker Desktop's name for your computer, where MySQL listens on port 3307. On Linux, add--add-host=host.docker.internal:host-gateway. The project at the end of this module uses a Docker network instead. --env-file .envpassesDB_USER,DB_PASSWORDandJWT_SECRETfrom your.envfile without typing secrets on the command line.with PID 1in the first log line proves the exec-formENTRYPOINTworked: Java itself is the first process.started by rootis fixed later in the Running as a non-root user lesson. Your timestamps and Java update number will differ.
COPY target/*.jar app.jar copies the jar and renames it, so the Dockerfile does not change when the version moves from 1.2.0 to 1.3.0. The jar is already compiled, so a JRE image (the Java runtime without the compiler) is enough. ShopLite is compiled with --release 17 and runs fine on a Java 25 runtime.
ENTRYPOINT in exec form makes java PID 1, so Spring Boot receives SIGTERM and shuts down gracefully. Words after the image name in docker run, such as --server.port=9090, are passed to the app as arguments.
./mvnw package to run on your computer first. The Multi-stage builds lesson moves that Maven build inside Docker.Next step
Check your understanding
12 quick questions