DEV Community

loading...

docker and java

vishwasnarayanre
I am technician
Updated on ・2 min read

First thing you need is a java -JRE,JDK installed on to your system with the docker installed with all the additional kernels like Hyper-V or the WSL2 installed on to the system.

First let's start by writing java programing language code.

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello docker world!"); 
    }
}
Enter fullscreen mode Exit fullscreen mode

To test that whether your program is working proper run and execute the program save the program as firstprogram.java

and use the command javac firstprogram.java

then you will find the output

Alt Text

So now in order to run the program through the docker container we need to have the JDK installed on to the Docker image thus we can go to the docker hub and get the current version of the JDK on to your Docker image.

https://hub.docker.com/_/openjdk/

This is the link that I have listed above.

Alt Text

you can also go to the github repository and also see the offical images that you might be able to use.

https://github.com/docker-library

Now lets start creating the docker file

Open Dockerfile and start the code

#alpine will be the base os or the webserver that we will be working on
FROM alpine will be working on
WORKDIR /root/program1
COPY firstprogram.java /root/program1

#Install JDK
#to add the openjdk8 for the environment
RUN apk add openjdk8 
ENV JAVA_HOME /usr/lib/jvm/java-1.9-openjdk
ENV PATH $PATH:$JAVA_HOME/bin

#for running the java porogram
RUN javac firstprogram.java

ENTRYPOINT java firstprogram
Enter fullscreen mode Exit fullscreen mode

then you can build by using the following command

docker run -t javafirstprogram .

then you can run the program by typing in the command

docker run javafirstprogram

then you will find the same output.

Alt Text

Thus, you have learnt to get the java program up and running.

Thank you

Discussion (2)

Collapse
thorstenhirsch profile image
Thorsten Hirsch

Please fix the typos in your code. Neither the Java code nor the Dockerfile work.

Collapse
vishwasnarayan5 profile image
vishwasnarayanre Author • Edited

fine I will fixed it please check if it works for you