Containerisation of Java applications
Containerisation is the process of creating a bundle of application code and all its dependancies.
This blog post explains various benefits of containerisation.
Let’s say, we have basic java application called java-app
with following directory structure and we want to containerise it.
java-app (repository root directory)
├── build.gradle
└── src
└── main
└── java
└── org.example
└── HelloWorld.java
Content of HelloWorld.java
package org.example;public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Content of build.gradle
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.com.github.johnrengelman:shadow:7.1.2"
}
}plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '7.1.2'
}group 'org.example'
version '1.0-SNAPSHOT'apply plugin: "com.github.johnrengelman.shadow"repositories {
mavenCentral()
}
In order to create docker image, we need to define Dockerfile and a script to build the docker image. We can keep both the files in repository root directory like this:
java-app
├── build.gradle
├── build_image.sh
├── Dockerfile
└── src
└── main
└── java
└── org.example
└── HelloWorld.java
Content of Dockerfile
FROM amazoncorretto:11COPY . /opt/java-app/WORKDIR /opt/java-app/ENTRYPOINT []
Content of build_image.sh
gradle clean shadowjardocker buildx build --platform linux/amd64 . -t java-app:latest --load
We can build the image using:
[root@DEV-BOX java-app]# sh -e build_image.sh[root@DEV-BOX java-app]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
java-app latest a258ee1690c4 3 minutes ago 447MB
Lets run our Java app using docker run command:
[root@DEV-BOX java-app]# docker run -it java-app:latest java -cp build/libs/java-app-1.0-SNAPSHOT-all.jar org.example.HelloWorld
Hello world!
The process remains same for more complex Java applications with multiple dependancies.