In this article we will run a Spring Boot Application in Docker Container.
Here we will use this SpringMVCFormValidator application for our use case.
Download the source code from the below link.
Once you download and unzip, you will get the below structure once you import it in Eclipse or any other IDE.
We need to perform the following steps
- Create the Dockerfile(I have already shared it in the attachment)
Dockerfile is a text file that contains instructions for building the Docker image. This is used by Docker to build the image which will be executed in the Docker container. Please find below the content of the Docker file
FROM openjdk:8
ADD target/SpringMVCFormValidator-1.0.jar SpringMVCFormValidator-1.0.jar
EXPOSE 8080
ENTRYPOINT [“java”, “-jar”, “SpringMVCFormValidator-1.0.jar”]
Let’s understand the instructions
FROM openjdk:8 – This will download the openjdk:8 image from Docker Hub(https://hub.docker.com). This openjdk 8 will be used for executing the jar file.
ADD target/SpringMVCFormValidator-1.0.jar SpringMVCFormValidator-1.0.jar – This will copy the SpringMVCFormValidator-1.0.jar from the target folder to the Docker image.
EXPOSE 8080 – Expose the port 8080 of the Docker Container for running the application.
ENTRYPOINT [“java”, “-jar”, “SpringMVCFormValidator-1.0.jar”] – ENTRYPOINT allows you to specify the startup command for an image. Here will run the jar file “SpringMVCFormValidator-1.0.jar”
2. Create the Spring Boot Project jar
Go to the SpringMVCFormValidator folder in the terminal and run the following Maven command.
mvn clean package
This will create the SpringMVCFormValidator-1.0.jar in the target folder.
3. Download and install Docker Desktop
Please download and install Docker Desktop from https://www.docker.com/products/docker-desktop.
Docker Desktop is an application for Mac or Windows that enables us to build and share containerized applications and microservices.
4. Build Docker Image
Run the below command in the terminal. This will create the image docker-spring-boot-example by reading the instructions in the earlier created Dockerfile.
docker build -f Dockerfile -t docker-spring-boot-example .
After this, run the below command to check the images. This will list all the images in the Docker.
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
docker-spring-boot-example latest c461069dca00 4 days ago 533MB
docker/getting-started latest 021a1b85e641 5 weeks ago 27.6MB
5. Run Docker Image in a Container
Let’s run the created image in the Docker Container by executing the below command.
docker run -p 8085:8080 docker-spring-boot-example
Here, 8085 – host machine port, 8080 – Container port
This will print the below output which basically states that the application got started.
Now hit http://localhost:8085 – Please note that the host port is 8085 as specified in the earlier Docker run command.