Containerize The Java Application Using Docker
Maven Install
we need to install the maven it is important to create the jar file of our application.
- Open your terminal ubuntu or WSL and run this command to check the maven presence.
✨ $ mvn -v- If the maven doesn’t install in the system install using this.
✨ $ sudo apt install maven- It will install the maven in our system once installation is finished recheck the installation using above mvn -v command.
Go where pom.xml file is present in your application locate that folder and run this command to create the jar file of application
✨ $ maven clean package- First it compiles our code.
- It create the jar file of the application in target folder of the application folder.
Docker File
That’s all now we can create the docker file.
- Open any text editor and create file name without any extension of this name Dockerfile.
- File name must same like this. if any typo on this name docker won’t build image.
FROM baseimage:tag
RUN apk update && apk add openjdk17-jre
ENV PATH="/usr/lib/jvm/java-17-openjdk-amd64/bin:${PATH}"
COPY target/[appname-0.0.1-SNAPSHOT.jar] [New-Name].jar
EXPOSE 8080
CMD ["java", "-jar", "[New-Name].jar"]
It is the sample Dockerfile for the application.
✨ FROM → It is the base image from the docker hub and tag of the image.
✨ RUN → It add the JDK to the image that help to run the any java application.
✨ ENV → This set the path for JDK installation.
✨ COPY → It copy our application jar file inside the image.
✨ EXPOSE → It will expose the image on default port number. It help to run a container.
✨ CMD → Finally this run the application whenever containers are created.
Docker image
Open the Terminal and go to the root directory where Dockerfile rely on. Now run this command to build a image.
✨ $ docker build -t [image-name]:tag [Dockerfile-PATH]- It build the image from the Dockerfile.
- image is build check the image using this command.
✨ $ docker imagesDocker Container
Now time to run the application in a container.
✨ $ docker run --name [container-name:tag] -p [EXPOSE-port:port-want-to-run] -d [image-name:tag]That’s all now the application will run on the container port you don’t need to run a application in IDE anymore.
If you want to publish your application or share your work follow the below steps.
Publish the image
- If you don’t have Docker Hub account create one, if you have login into account.
- Create a New Repository.
If you want to be easy Pushing rename the image with similar to the [USERNAME/REPOSITORY] name that similar to the Docker Hub.
Now open the terminal and use this command.
✨ $ docker push [username/repositoryname]:tagIt’s Done making it public any one have the docker hub account in the world can access pull our image and use the application from creating the container.

Comments
Post a Comment