Tuesday, March 31, 2020

Docker + Java Application Example


As, we have mentioned earlier that docker can execute any application.
Here, we are creating a Java application and running by using the docker. This example includes the following steps.
  1. Create a directory
  2. Directory is required to organize files. Create a director by using the following command.
    1. $ mkdir  java-docker-app  
     See, screen shot for the above command.
    Docker Java application 1

  3. Create a Java File
  4. Now create a Java file. Save this file as Hello.java file.
    Hello.java
    1. class Hello{  
    2. public static void main(String[] args){  
    3. System.out.println("This is java app \n by using Docker");  
    4. }  
    5. }  
    Save it inside the directory java-docker-app as Hello.java.

  5. Create a Dockerfile
  6. After creating a Java file, we need to create a Dockerfile which contains instructions for the Docker. Dockerfile does not contain any file extension. So, save it simple with Dockerfile name.
    Dockerfile
    1. FROM java:8  
    2. COPY . /var/www/java  
    3. WORKDIR /var/www/java  
    4. RUN javac Hello.java  
    5. CMD ["java""Hello"]  
    Write all instructions in uppercase because it is convention. Put this file inside java-docker-app directory. Now we have Dockerfile parallel to Hello.java inside the java-docker-app directory.
    See, your folder inside must look like the below.

    Docker Java application 2

  7. Build Docker Image
  8. After creating Dockerfile, we are changing working directory.
    1. $ cd   java-docker-app  
    See, the screen shot.
    Docker Java application 3
    Now, create an image by following the below command. we must login as root in order to create an image. In this example, we have switched to as a root user. In the following command, java-app is name of the image. We can have any name for our docker image.
    1. $ docker build -t java-app .      
     See, the screen shot of the above command.
    Docker Java application 4
    After successfully building the image. Now, we can run our docker image.

  9. Run Docker Image
  10. After creating image successfully. Now we can run docker by using run command. The following command is used to run java-app.
    1. $ docker run java-app  
     See, the screen shot of the above command.
    Docker Java application 5
    Here, we can see that after running the java-app it produced an output.
    Now, we have run docker image successfully on your system. Apart from all these you can also use other commands as well.

Reference:


Previous Post
Next Post

1 comment: