Docker Java Example

We shall learn following items in this Docker Java Example :

Build Docker Image with Java Application

1 Create a directory

A separate directory is useful to organise docker applications. For this Java Example, create a directory somewhere with name of your choice. We shall use the name java-application

2 Create Java Application

Create a simple Java File, in the directory java-application, with name HelloWorld.java containing the following content.

</>
Copy
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("HelloWorld from Java Application running in Docker.");
    }
}

3 Dockerfile

Create a file with name Dockerfile. Dockerfile contains instructions to prepare Docker image with our Java Application.

Following is the content of Dockerfile.

</>
Copy
FROM java:8
RUN javac HelloWorld.java
CMD ["java", "HelloWorld"]

4 Verify contents of java-application directory

</>
Copy
java-application$ ls
Dockerfile  Hello.java

5 Build docker image

Login as root user. Navigate into java-application directory and run the following command. Instructions in the Dockerfile are executed.

</>
Copy
$ docker build -t java-application .