Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to create a Java Docker Container?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.


class Sample{
     public static void main(String args[]){
         System.out.println("Welcome to GeeksForGeeks");

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
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.

Create the Dockerfile

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 .

Build the Docker Image

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

Running the Docker Container

You can see that the program has been executed successfully and the result has been printed after running the Container.

My Personal Notes arrow_drop_up
Last Updated : 05 Nov, 2020
Like Article
Save Article
Similar Reads
Related Tutorials