Build And Deploy Java Application With Docker | Step-By-Step Tutorial
Last Updated :
08 Apr, 2024
Docker is an OS-level virtualization that helps to build and deploy any program. Docker is used to utilize the resources, and it is compatible with all operating systems.
What Is Docker Container?
The Docker container is the part of Docker that provides a lightweight isolation environment for running applications. It is used because it takes fewer resources and helps to build, test, and deploy the application in a very small and easy way.
Prerequisite
- The docker should be installed and in running condition.
- We should have a proper Java application that we have to deploy.
- Java should be installed on your system.
Step-By-Step Process To Building Java application
- Java code: I have a simple Java application that will print "Hello World" on the screen. We can create your Java project.
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class HelloWorld {
public static void main(String[] args) throws IOException {
// Create a new HTTP server listening on port 8001
HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);
// Create a context for handling requests
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
// Set the response headers
exchange.getResponseHeaders().set("Content-Type", "text/html");
exchange.sendResponseHeaders(200, 0);
// Get the response body stream
OutputStream responseBody = exchange.getResponseBody();
// Write the HTML content to the response body
String htmlResponse = "<html><body><h1>Hello, World!</h1></body></html>";
responseBody.write(htmlResponse.getBytes());
// Close the response body stream
responseBody.close();
}
});
// Start the server
server.start();
// Output a message indicating the server has started
System.out.println("Server is listening on port 8001...");
}
}
Now, Before deploying this application with the Docker we have to build it with the help of Dockerfile.
Dockerfile For Java Application | Step-By- Step Guide
It is a file where we writes all the process of building and accessing the application. In this file we use "YML" language which is a easy to learn and also called human language.
Step 1: Write the Dockerfile For Java Application.
Following is the Dockerfile for this application, the process will be same for all your java applications.
# Use a specific version of OpenJDK
FROM openjdk:11
# Set the working directory
WORKDIR /javaapp
# Copy only the necessary source files
COPY HelloWorld.java .
# Compile the Java program
RUN javac HelloWorld.java
# Set the default command to run the Java program
CMD ["java", "HelloWorld"]
- FROM: This command is use to specify the version of the language which help to run the application.
- WORKDIR: This command is use to specify a directory where the all process will happen.
- COPY: This is use to copy the files and resources from your local system to docker container.
- RUN: This is use to run any command , it can be language command, or linux command or anything which helps do download the dependencies, building the application, compilation etc.
Step 2: Build The Docker image by using dockerfile.
Now, After creating the Dockerfile we have to use Docker for building the image and container for deployment.
- Docker file should be present in the main folder of your project.
- First we have to build the docker image
docker build -t "any name for your docker image" .
docker build -t helloworld

Step 3: List all the Docker images.
- For listing the all docker images
Docker images

Steps To Deplo The Java Application
After building the Docker image, now we are ready to deploy the application with Docker.For deployment we have to create the Docker container.
Step 1: Run The Docker container using Docker image.
- To create the docker container from the docker images.
docker run -p "port" -d "your image name"
docker run -p 8001:8001 -d helloworld

Step 2: List all the containers in docker.
- To list all the running containers.
docker ps

Now, We can access the java application with the help of localhost:port that you have given while creating the docker container.
Open browser and type
127.0.0.1:8001

Conclusion
We can build and deploy any application with Docker. Docker is a very optimized way to build a application and deploy on the server. In the Docker the important thing to learn is how the application will Compile and creating Dockerfile. Docker is very efficient way to deploy a application because it takes less resources.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences
4 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read