Dockerize a Java Application

Dockerize a Java Application

My DEVOPS Journey

ยท

2 min read

Hello folks! I'm back with another blog on docker.

To check out my detailed blog on docker, click here.

The above image summarizes the whole process of dockerization.

Dockerize a Java Application

Let's now dockerize a simple Java application.

The Java application is nothing but a Java program that checks whether the number is even or odd.

Note: I wrote Java code and Dockerfile in VS Code and used docker build command in VS Code terminal itself.

Prerequisites - Docker desktop, WSL2

Link to download docker desktop

Link to download WSL2

Step - 1:

Create a .java file and write the code

import java.util.Scanner;
public class demo {
    public static void main(String[]args){
         Scanner sc = new Scanner(System.in);
         System.out.print("Enter a number : ");
         int n = sc.nextInt();
         if(n%2 == 0){
            System.out.println("The number " + n + " is EVEN");
         }else{
            System.out.println("The number " + n + " is ODD");
         }
         sc.close();
    }
}

My java file name is "demo"

Step - 2:

Write a Dockerfile in VS code

FROM openjdk
WORKDIR /app
COPY . /app
RUN javac demo.java
CMD ["java","demo"]

Step - 3:

Now run docker build command in the terminal(vs code) to build the docker image.

docker build -t evenorodd .

// evenorodd is the image name which we build
// "." is the current directory

Let's check whether the image is built or not.

For that, open Docker desktop and check whether there's any image is created or not

We can also open WSL and run a command to check

Step - 4:

Now, we must implement Docker run command to create a container out of the image

docker run -it --name=javaprogram -d evenorodd

// -it is used to run in an interactive environment
// "javaprogram" is the name of the container which are creating
// -d is used to run in detach mode
// "evenorodd" is the image name which we already built in the previous step

Let's check whether we created the container or not

Open WSL and run docker ps command

Step - 5:

Now, we are at the final step

docker exec -it javaprogram java demo

// "java" and "demo" are used in dockerfile's CMD.
// They are defaults which omit the executable

So, we can see that our Java application is working fine. That's great!

So that's it for the blog guys. I hope you found it useful.

To contact me:

Twitter: https://twitter.com/Chris__Jonathan

LinkedIn: https://www.linkedin.com/in/chris-jonathan/

Thank you guys ๐Ÿ˜Š

ย