Docker Java Example
We shall learn following items in this Docker Java Example :
- Build a Docker Image with Java Application
- Run the Docker Image with Java Application
- Save the Docker image to a tar file
- Copy the docker image to another computer and run it
Build Docker Image with Java Application
1 Create a directory
A separate directory is useful to organise docker applications. For this Java Example, create a directory somewhere with name of your choice. We shall use the name java-application
2 Create Java Application
Create a simple Java File, in the directory java-application, with name HelloWorld.java containing the following content.
</>
Copy
public class HelloWorld {
public static void main(String[] args) {
System.out.println("HelloWorld from Java Application running in Docker.");
}
}
3 Dockerfile
Create a file with name Dockerfile. Dockerfile contains instructions to prepare Docker image with our Java Application.
Following is the content of Dockerfile.
</>
Copy
FROM java:8
RUN javac HelloWorld.java
CMD ["java", "HelloWorld"]
4 Verify contents of java-application directory
</>
Copy
java-application$ ls
Dockerfile Hello.java
5 Build docker image
Login as root user. Navigate into java-application directory and run the following command. Instructions in the Dockerfile are executed.
</>
Copy
$ docker build -t java-application .
