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, and Java JRE and the setting of paths and environment variables. This might seem like 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.

Build your Docker Java Image

Building your own customized docker image requires a dockerfile. Dockerfile is a source code of a docker image dockerfile consisting of instructions required for the docker image to build.

A Sample Dockerfile for Java

FROM java:8
WORKDIR /var/www/java
COPY . /var/www/java
RUN javac Sample.java
CMD ["java", "Sample"]

After writing the docker file you use the command mentioned below to build the docker image.

docker run -it <name of dockerfile>

Test the Java Web Application Without Docker

Follow the steps mentioned below to test and deploy the Java web application without docker.

Step 1: Pull the source code which is available in the GitHub by the https URL.

Step 2: Install maven in the virtual machine which is package manager of java application use the following command to build the .war application which is going to deploy in the form virtualization form.

mvn clean package

Step 3: You can tomcat to deploy the web application or you can use the local host to test the application by using the http://localhost:8080.

Create a Dockerfile for Java

To deploy java application in the form of container by using docker first you need to create dockerfile as shown in below.

Step 1: We need to select the base image you need to pull the base image by using the following instruction you can start your dockerfile. to know the syntax of dockerfile refer to What is Dockerfile Syntax?

FROM java:8

Step 2: Set the working directory for the image. With this command, Docker is told to make this path the default location for all ensuing commands. By doing this, we can use relative paths depending on the working directory rather than having to spell out entire file paths.

WORKDIR /var/www/java

Step 3: Copy the files of java into the required path here we can say to our working directory and give the command to run the java process by using the CMD command and start the process by using the following command. To know more docker commands refer to Docker – Instruction Commands.

COPY . /var/www/java
RUN javac Sample.java
CMD ["java", "Sample"]

Create a Dockerfile For Java Web Application

If you want to run the java application in the form of containers then you need to first build an image of the application to build an image you need dockerfile following is the sample dockerfile for java web application.

Dockefile to Run Java Application As Container

Before writing the dockerfile mentioned below you need to build an .war file package using maven with it download all the dependencies required to download for the application and make it ready to deploy the application.

FROM tomcat:8.0.20-jre8
COPY target/java-web-app*.war /usr/local/tomcat/webapps/java-web-app.war

We are using the tomcat as an base image and coping the java-web-app*.war file which is build using maven will copied to the /usr/local/tomcat/webapps/java-web-app.war.

Build an Docker Image

Step 1: Create a new Java project

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.

Java
class Sample{
     public static void main(String args[]){
         System.out.println("Welcome to w3wiki");
     }
}
  1. Class Definition (class Sample):
    • This line defines a class named Sample. In Java, every piece of code must be inside a class.
  2. Main Method (public static void main(String args[])):
    • public: This means the method is accessible from anywhere.
    • static: This means that the method belongs to the class, not instances of the class. You can call this method without creating an object of the class.
    • void: This means the method does not return any value.
    • main: This is the name of the method. The Java Virtual Machine (JVM) looks for the main method as the entry point of any Java program.
    • String args[]: This is an array of String objects. It allows the program to accept any number of command-line arguments.
  3. Printing a Message (System.out.println("Welcome to w3wiki")):
    • System.out: This is a standard output stream that is used to output data.
    • println: This is a method that prints the argument passed to it (in this case, “Welcome to w3wiki”) and then moves to a new line.

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.

  • FROM java:8:
    • The Docker image’s base image is specified in this line. An approved Docker image that has the Java Development Kit (JDK) version 8 installed is denoted by the hashtag java:8. All the tools and environment needed to compile and run applications written in Java are included within this fundamental image.
  • WORKDIR /var/www/java:
    • This line switches the container’s working directory to /var/www/java. This directory serves as where all future commands (such as COPY, RUN, etc.) will be carried up. The directory will be created if it is yet to be created.
  • COPY . /var/www/java:
    • This line transfers each file to the container’s /var/www/java directory from the host machine’s current directory, containing the Dockerfile. This usually includes any other resources the application need in alongside your Java source files.
  • RUN javac Sample.java:
    • This line utilizes the Java compiler (javac) to compile the Java source file Sample.java. The Java Virtual Machine (JVM) will be able to execute the right bytecode file Sample.class as a consequence of this. Based of the COPY command, the command believes that Sample.java is in the /var/www/java directory.
  • CMD ["java", "Sample"]:
    • The command to be performed when the container starts is given in this line. In order to start the JVM and run the Sample class, it runs the java command here. The Java application’s entry point, a public static void main(String[] args) method, should be present within the Sample class. The JSON array format, which is the preferred format for defining the command and its arguments, is used within the CMD instruction.

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 .
  • sudo: Runs the command with superuser (administrator) privileges.
  • docker build: Tells Docker to build a new image.
  • -t java-demo: Tags (names) the new image as java-demo.
  • .: Uses the current directory (where the command is run) as the context for the build, looking for a Dockerfile there.

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
  • sudo: Runs the command with superuser (administrator) privileges.
  • docker: Calls Docker, a platform for running applications in containers.
  • run: Tells Docker to run a container.
  • -it: Makes the container interactive and attaches a terminal session.
  • java-demo: The name of the Docker image to run.

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

View Local Images

Lists all the pulled images which are present in our system.

$ docker images

Tag Images

f you use the following command then you can push only the latest tag of docker image to the registry.

docker push my_image

If you want to push all the tags of docker image then you need tot use the following command.

docker push my-image -a

Create a .dockerignore File

While creating an docker image there will be some files which not required to include in the docker image and also if u include all this file in the docker image than the size of the image will get increased which will increase the latancey of the application.

.dockerignore file will help us to ignore all the file which not required for the docker image. As shown in the following.

To exclude the files which is shown below .file extension and all the files which are already present in the log directory.

logs/*
*.png

Docker Compose in JAVA

You can define and manage multi-container Docker applications using the assistance of Docker Compose. Using a single YAML file for configuring several services, including databases, message brokers, and other dependencies, allows for easier for Java developers to run applications with many services. Using this YAML file, developers can set up an entire environment with a single command as it specifies the services, networks, and volumes required to run the application. Java applications may be carried out in isolated containers with Docker Compose, ensuring consistency across development and production environments. By utilizing the features of containerization, this approach not only make setup simpler but also improves the scalability and maintainability of applications written in Java. For more detail about to for docker compose for java application refer this link.

Docker Java Image – FAQs

What is the Docker in Java?

A Docker in Java is a Java library that allows you to create, run, and manage Docker containers.

Why Use Docker With Java?

Docker containers are portable, meaning that they can be run on any machine that has Docker installed. This makes it easy to deploy Java applications to different environments, such as development, staging, and production.

Do you need Docker for Java?

You don’t need Docker to run Java programs; you can execute them directly on your machine with the Java Development Kit (JDK). However, Docker can be useful for creating consistent environments, simplifying deployment, and managing dependencies across different syste

What is Docker in Spring Boot?

Docker in Spring Boot is a tool that allows you to package a Spring Boot application along with its dependencies into a single container, ensuring consistency across different environments. This makes it easy to deploy and run the application on any system that supports Docker.

How to create a Docker in Java?

To create a Docker container for a Java application, first write a Dockerfile specifying a base Java image, copying your application JAR file, and setting the command to run the JAR. Then, build the Docker image using docker build -t your-image-name . and run it with docker run your-image-name.



Contact Us