How to create a Java Docker Container?
Java is one of the most popular languages and supports many enterprise applications. Running Java on local machines requires the installation of Java IDE, Java JDK, Java JRE, and requires the setting of paths and environment variables. This might seem to be a hefty task especially if you just want to run a simple program. In this article, we will discuss how to run Java inside Docker Containers.
Step 1: Create a Sample Java Application
We will create a simple Java application with a print statement inside it. Refer to the program below. Note that your file name and Main class name should exactly match each other.
Step 2: Create the Dockerfile
Have a look at the Dockerfile below.
FROM java:8 WORKDIR /var/www/java COPY . /var/www/java RUN javac Sample.java CMD ["java", "Sample"]
In the above Dockerfile, we have pulled the Java base Image from DockerHub. We have set the working directory and copied the files to the working directory. After that, we have compiled our Java application and run the executable.
Note that your directory structure should look like this.
Step 3: Build the Docker Image
Now, you can use the Docker build command to build the Docker Image.
sudo docker build -t java-demo .
Step 4: Running the Docker Container
After you have built your Docker Image, you can run your Docker container using the Docker run command.
sudo docker run -it java-demo
You can see that the program has been executed successfully and the result has been printed after running the Container.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.