ChildOfCode


Code, Maker, Robotic, Open Source. Knowledge Bases


Docker - Create a Java development environment

Yes is Docker Again 🐳. !
Well my work need to switch many different programming language and different development environment .
Docker is really helpful

There are two way to compile and execute you java code. Compile and execute inside the Docker or compile and execute outside the Docker instance.

Compile your app and execute inside the Docker container

1. Let Create a Dockerfile with below configuration

FROM openjdk:8  
COPY . /usr/src/myapp  
WORKDIR /usr/src/myapp  
RUN javac Code.java  
CMD ["java", "Code"] 

FROM openjdk:8 Get the openjdk 8 Images from docker hub'

COPY . /usr/src/myapp Copy myapp folder inside docker

WORKDIR /usr/src/myapp Create a place to store the source code

RUN javac Code.java Compile the java code

CMD ["java", "Code"] Execute the Java application

2.Create a folder call myapp inside a folder create a java file

Create java file calling Code.java with code below.

public class Mycode {

    public static void main(String args[]){  

        System.out.println("Hello Docker");   

    }
}

3.Build the image by Dockerfile

docker build -t java_env .

4. Run the Docker container Image

docker run -it --rm java_env

you should see the 'Hello Docker' output on your terminal .

Compile and execute outside the Docker container

1. Let Create a Dockerfile with below configuration

FROM openjdk:8  
COPY . /usr/src/myapp  
WORKDIR /usr/src/myapp

2.Create a java file

Create java file calling Mycode.java with code below.

public class Mycode {

    public static void main(String args[]){  

        System.out.println("Hello Java");   

    }
}

3.Build the image by Dockerfile

docker build -t java_env .

4. Compile the Java source code

docker run --rm -v "$PWD":/usr/src/app -w /usr/src/app java_env javac Mycode.java

After run the command docker will compile and create a file name Mycode.class on you folder.

4. Execute the Java application

docker run --rm -v "$PWD":/usr/src/app -w /usr/src/app java_env java Mycode

Execute the java application outside Docker container, You will see the output message "Hello Java".