A Basic Dockerfile
Run the following command at the root of our project to build a Dockerfile. This command will create an empty Dockerfile in the current directory. After creating the Dockerfile, you can proceed to define the necessary instructions for building your Docker image as mentioned in below steps.
$ touch Dockerfile
Add configuration to dockerize the Spring Boot application
Now we have a working Spring Boot Application, To dockerize an application, now paste the following content into the Dockerfile:
FROM openjdk:18
WORKDIR /app
COPY ./target/spring-0.0.1-SNAPSHOT.jar /app
EXPOSE 8080
CMD ["java", "-jar", "spring-0.0.1-SNAPSHOT.jar"]
The above file contains the following information:
FROM openjdk:18
: This line specifies the base image for the Docker container. In this case, it uses the official OpenJDK image tagged with version 18. This image provides a runtime environment for Java applications.
WORKDIR /app
: This line sets the working directory inside the container to/app
. All subsequent commands will be executed relative to this directory.COPY ./target/spring-0.0.1-SNAPSHOT.jar /app
: This command copies the Spring Boot application JAR file from the host machine’s./target
directory to the/app
directory inside the container. It’s assuming that you’ve built the Spring Boot application and the JAR file is available in the specified location.EXPOSE 8080
: This line informs Docker that the container will listen on port 8080 at runtime. However, it doesn’t actually publish the port. It’s merely a documentation of which ports the container is expected to use.CMD ["java", "-jar", "spring-0.0.1-SNAPSHOT.jar"]
: This command specifies the default command to run when the container starts. It launches the Spring Boot application by executing thejava -jar
command with the Spring Boot JAR file as its argument.
Now create a docker image by using the docker build command:
$ docker build -t [name:tag] .
- -t: Name and tag for the image
- . : The context for the build process
Once the build process has been completed, you will receive the id and tag of your new image.
How To Dockerize A Spring Boot Application With Maven ?
Docker is an open-source containerization tool used for building, running, and managing applications in an isolated environment. A container is isolated from another and bundles its software, libraries, and configuration files. In this article, to dockerize a Spring Boot application for deployment purposes, we will learn how to create a spring boot app, and how to create a docker image for the spring boot app and we will run it on the docker container.
Prerequisites: Before continuing any further, please ensure that node and docker are installed on your machine. If required, visit the Java Installation Guide or the Docker Installation Guide.
Contact Us