Docker Java application example

Here in this tutorial we you will learn to create a java hello world application in docker.

Follow these steps to make a java application run in docker:

1. Create a directory

Create this directory Just to keep all the files in place and organize them.$ mkdir docker-java-app

2. Create a Java file

Create a sample java file inside the above created directory. For example name it as HelloWorld.java

$ cd docker-java-app

class HelloWorld{  
  public static void main(String[] args){  
    System.out.println("Hello World java app - in Docker");  
    }  
} 

3. Create a Dockerfile

Dockerfile does not contain any file extension so please be careful in this with the name “Dockerfile”.FROM java:8
COPY . /var/www/java
WORKDIR /var/www/java
RUN javac HelloWorld.java
CMD [“java”, “HelloWorld”]

4. Build Docker Image

Please make sure you run the docker build command in the directory where the Dockerfile is present, in our case it is the “docker-java-app” directory where both the files are kept.We can have any name for the image, for example here we named it as “java-hello-app”.$ docker build -t java-hello-appThis command will call the docker daemon to build this image.

5. Run Docker Image

Just a simple command to run the image$ docker run java-hello-appWhich should give the following output:Hello World java app - in Docker

Summary

In this tutorial we learnt how to create a docker based simple java application, we learnt how to build an image and run it on docker using docker command CLI.

We hope you enjoyed learning this.


Leave a Comment