Docker Java: Dockerize a Java Application

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 288 of 306

To dockerize a Java application means packaging the JAR, a Java runtime and the start command into one container image that runs the same way on any machine with Docker. The server no longer needs Java installed, and "it works on my machine" problems disappear because everyone runs the exact same image. Containers are also the standard way to deploy to the cloud and to Kubernetes.

This lesson takes the CourseServer app from Java Deployment, writes a Dockerfile for it, improves it step by step (multi-stage build, non-root user, memory limits, health checks) and finishes with Docker Compose. All examples were run with Docker 28 and JDK 21.


Docker Basics for Java Developers

TermMeaningJava comparison
ImageA read-only package: OS files + Java + your JARLike a JAR, but includes the runtime
ContainerA running instance of an imageLike a running JVM process
DockerfileThe recipe that builds an imageLike pom.xml for the image
RegistryA server that stores images (Docker Hub, GHCR)Like Maven Central
TagA version label, e.g. course-server:1.1.0Like the project version

How it works:

  • An image is built in layers. Each Dockerfile instruction adds a layer, and unchanged layers are reused from cache on the next build.
  • A container is isolated from the host: it has its own file system, network and process list, but shares the host's Linux kernel.

Write Your First Dockerfile for a Java App

Start with the JAR you already built (target/course-server-1.1.0.jar) and the official Eclipse Temurin Java image.

# Dockerfile
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/course-server-1.1.0.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
InstructionWhat it does here
FROM eclipse-temurin:21-jreBase image: Ubuntu + Java 21 runtime (no compiler)
WORKDIR /appCreates /app and makes it the current folder
COPY ... app.jarCopies the JAR from your project into the image
EXPOSE 8080Documents the port the app listens on
ENTRYPOINT [...]The command that runs when the container starts
docker build -t course-server:1.1.0 .
docker image ls course-server --format "{{.Repository}}:{{.Tag}}"
[+] Building 6.4s (8/8) FINISHED
 => [internal] load build definition from Dockerfile
 => [1/3] FROM docker.io/library/eclipse-temurin:21-jre
 => [2/3] WORKDIR /app
 => [3/3] COPY target/course-server-1.1.0.jar app.jar
 => exporting to image
 => => naming to docker.io/library/course-server:1.1.0
course-server:1.1.0

How it works:

  • -t course-server:1.1.0 names and tags the image. Always tag with the real version, not only latest, so you know what each server runs.
  • The final . is the build context: the folder whose files COPY can see.
  • Use the -jre image to run apps. The -jdk image includes javac and other tools a running server does not need, making the image larger.

Run a Java Container

docker run -d --name course -p 8080:8080 -e APP_ENV=prod course-server:1.1.0
docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
docker logs course
curl -s -w "\n" http://localhost:8080/health
NAMES     IMAGE                 STATUS         PORTS
course    course-server:1.1.0   Up 3 seconds   0.0.0.0:8080->8080/tcp
CourseServer 1.1.0 started on port 8080 (env=prod, java=21)
{"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":3}

Common docker run Options

OptionExampleMeaning
-d-dRun in the background
--name--name courseA fixed name instead of a random one
-p host:container-p 80:8080Publish container port 8080 on host port 80
-e KEY=value-e APP_ENV=prodSet an environment variable
--env-file--env-file app.envLoad many variables from a file
--memory--memory 512mHard memory limit for the container
--restart--restart unless-stoppedRestart after crashes and Docker restarts
--rm--rmDelete the container when it stops

How it works:

  • -p 8080:8080 maps the host's port to the container's port. Without it, the app runs but nobody outside the container can reach it.
  • The app reads APP_ENV with System.getenv, exactly as on a normal server. Environment variables are the main way to configure containers, as covered in Java Environment Variables.
  • docker logs shows everything the JVM printed to stdout and stderr, so Java apps in containers should log to the console, not to files.

Stop a Java Container Gracefully

docker stop sends SIGTERM to the main process, waits 10 seconds, then sends SIGKILL.

docker stop course
docker logs course | tail -n 2
docker inspect course --format "exit code: {{.State.ExitCode}}"
Shutting down...
Stopped.
exit code: 143

How it works:

  • The exec form ENTRYPOINT ["java", ...] makes java process 1 in the container, so it receives the signal directly and the shutdown hook runs.
  • The shell form ENTRYPOINT java -jar app.jar would start /bin/sh as process 1. The shell does not pass SIGTERM on, so Docker kills the JVM after 10 seconds without a clean shutdown.
  • Exit code 143 (128 + 15) means "stopped by SIGTERM", which is the normal result.

Multi-Stage Builds: Build the JAR Inside Docker

The first Dockerfile needs a JAR built on your machine. A multi-stage build compiles the code inside Docker too, so the build only needs Docker, not Maven or a JDK.

# Dockerfile
# ---------- stage 1: build ----------
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /build
COPY pom.xml .
RUN mvn -q dependency:go-offline           # cached until pom.xml changes
COPY src ./src
RUN mvn -q -DskipTests package

# ---------- stage 2: run ----------
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /build/target/course-server-*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t course-server:1.1.0 .
# change one line in a .java file, then build again
docker build -t course-server:1.1.0 . 2>&1 | grep -E "CACHED|RUN mvn"
 => CACHED [build 2/6] WORKDIR /build
 => CACHED [build 3/6] COPY pom.xml .
 => CACHED [build 4/6] RUN mvn -q dependency:go-offline
 => [build 6/6] RUN mvn -q -DskipTests package

How it works:

  • Only the last stage becomes the final image. Maven, the JDK and the source code stay in the build stage and are thrown away.
  • Copying pom.xml before src is the key trick. Dependencies are downloaded in their own layer, which stays cached while you only change Java code. Rebuilds take seconds instead of minutes.
  • Add a .dockerignore file with target/ and .git/ so those folders are not sent to Docker as part of the build context.

Run the Container as a Non-Root User

By default the process inside a container runs as root. Create a normal user and switch to it.

FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=build --chown=app:app /build/target/course-server-*.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t course-server:1.1.0 .
docker run --rm --entrypoint id course-server:1.1.0
uid=999(app) gid=999(app) groups=999(app)

How it works:

  • USER app applies to every later instruction and to the running container. If the app is attacked, the attacker is not root inside the container.
  • --chown=app:app gives the copied JAR to the new user in the same layer.
  • --entrypoint id replaces java for one run, a quick way to see which user the image runs as.

Set Java Memory Correctly in Containers

The JVM is container-aware: it reads the container's memory limit, not the host's total memory. By default it uses only 25% of that limit for the heap, which is low for a container that runs nothing else.

docker run --rm --memory 512m --entrypoint java course-server:1.1.0 \
  -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E " MaxHeapSize"

docker run --rm --memory 512m -e JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75" \
  --entrypoint java course-server:1.1.0 \
  -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E " MaxHeapSize"
   size_t MaxHeapSize                              = 134217728                                 {product} {ergonomic}
   size_t MaxHeapSize                              = 402653184                                 {product} {ergonomic}
SettingHeap with --memory 512m
Default (25%)128 MB
-XX:MaxRAMPercentage=75384 MB
-Xmx300m300 MB (fixed, ignores the limit)

How it works:

  • --entrypoint java replaces the image's ENTRYPOINT, so the arguments after the image name go to java instead of being added to java -jar app.jar.
  • 134217728 bytes is 128 MB (25% of 512 MB); 402653184 bytes is 384 MB (75%).
  • MaxRAMPercentage scales automatically when you change --memory, so the same image fits small and large containers. Leave about 25% for metaspace, threads and other non-heap memory.
  • JAVA_TOOL_OPTIONS is read by every JVM automatically, so you can change JVM flags without editing the ENTRYPOINT.

Add a Health Check to the Java Image

A HEALTHCHECK lets Docker test whether the app actually answers, not just whether the process exists.

HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
  CMD bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /health HTTP/1.0\r\n\r\n" >&3 && grep -q "\"UP\"" <&3'
docker build -t course-server:1.1.0 .
docker run -d --name course -p 8080:8080 course-server:1.1.0
sleep 15
docker ps --format "{{.Names}}: {{.Status}}"
course: Up 15 seconds (healthy)

How it works:

  • The check uses only bash and its built-in /dev/tcp device, so no extra tool such as curl has to be installed in the image.
  • --start-period=20s gives the JVM time to start before failed checks count.
  • After 3 failed checks in a row, the status becomes (unhealthy). Orchestrators such as Docker Swarm and Compose depends_on conditions use this status.

Real-World Example: Dockerize a Java Application With Docker Compose

Docker Compose describes the whole setup in one file: the image build, ports, environment, memory, restart policy and health check. This is the final layout of the project:

course-server/
├── Dockerfile
├── .dockerignore
├── compose.yaml
├── app.env
├── pom.xml
└── src/main/java/com/gocourse/app/CourseServer.java
# Dockerfile
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /build
COPY pom.xml .
RUN mvn -q dependency:go-offline
COPY src ./src
RUN mvn -q -DskipTests package

FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=build --chown=app:app /build/target/course-server-*.jar app.jar
USER app
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \
  CMD bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /health HTTP/1.0\r\n\r\n" >&3 && grep -q "\"UP\"" <&3'
ENTRYPOINT ["java", "-jar", "app.jar"]
# compose.yaml
services:
  course-server:
    build: .
    image: course-server:${APP_VERSION:-dev}
    ports:
      - "8080:8080"
    env_file: app.env
    mem_limit: 512m
    restart: unless-stopped
    stop_grace_period: 20s
# app.env
APP_ENV=prod
APP_PORT=8080
APP_VERSION=1.1.0 docker compose up -d --build
sleep 20
docker compose ps --format "table {{.Service}}\t{{.Image}}\t{{.Status}}"
curl -s -w "\n" http://localhost:8080/health
SERVICE         IMAGE                 STATUS
course-server   course-server:1.1.0   Up 20 seconds (healthy)
{"status":"UP","version":"1.1.0","env":"prod","uptimeSeconds":20}

Roll back by starting the previous tag, which is still on the machine:

APP_VERSION=1.0.0 docker compose up -d --no-build
sleep 3
curl -s -w "\n" http://localhost:8080/health
[+] Running 1/1
 ✔ Container course-server-course-server-1  Started
{"status":"UP","version":"1.0.0","env":"prod","uptimeSeconds":3}

How it works:

  1. One command to build and run. docker compose up -d --build runs the multi-stage build, tags the image with APP_VERSION, and starts the container with all options from compose.yaml.
  2. Same config pattern as before. env_file: app.env uses the same file format as the systemd service in Run Java as a Service. Secrets stay out of the image.
  3. Production settings. mem_limit caps memory, MaxRAMPercentage sizes the heap to that cap, ExitOnOutOfMemoryError makes the JVM exit on OOM, and restart: unless-stopped starts it again. stop_grace_period gives the shutdown hook up to 20 seconds.
  4. Fast rollback. Every release is a tagged image. Switching APP_VERSION and running up -d --no-build replaces the container in seconds: Compose stops the old container with SIGTERM, starts one from the 1.0.0 image, and /health confirms the version.
  5. Ready for registries. To use the image on other servers, docker tag course-server:1.1.0 ghcr.io/gocourse/course-server:1.1.0 and docker push it, then pull the same tag anywhere.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Docker Java: Dockerize a Java Application and get answers drawn from it.

Signed-in readers only.