Dockerfile for Spring Boot
This guide explains how to create a Dockerfile for your Spring Boot application to run it inside a Docker container.
Prerequisites
Before you create the Dockerfile, ensure you have the following:
- Your Spring Boot application packaged as a
.jarfile (usingmvn packageorgradle build). - Docker installed on your system.
Steps to Create a Dockerfile
-
Create a Dockerfile: In the root directory of your Spring Boot project, create a file named
Dockerfile(without any file extension). -
Dockerfile Contents:
# Step 1: Use a base image that includes Java
FROM openjdk:17-jdk-slim
# Step 2: Set the working directory in the container
WORKDIR /app
# Step 3: Copy the .jar file from your local system to the container
COPY target/your-application.jar app.jar
# Step 4: Expose the port on which your Spring Boot app will run
EXPOSE 8080
# Step 5: Define the command to run the Spring Boot application
ENTRYPOINT ["java", "-jar", "app.jar"]
Explanation:
- FROM openjdk:17-jdk-slim: This sets the base image for the container. We're using an OpenJDK 17 image for the Java environment.
- WORKDIR /app: Defines the working directory inside the container. All subsequent commands will run in this directory.
- COPY target/your-application.jar app.jar: This copies the your-application.jar file from your local machine into the /app directory inside the container. Replace your-application.jar with your actual JAR file name.
- EXPOSE 8080: Exposes port 8080, which is the default port Spring Boot apps run on.
- ENTRYPOINT ["java", "-jar", "app.jar"]: This specifies the command to run when the container starts. It runs the Spring Boot application using the java -jar command.
- Build the Docker Image: Once the
Dockerfileis created, you can build the Docker image using the following command: text
docker build -t spring-boot-app .
- Run the Docker Container: After the image is built, you can run the container using: text
docker run -p 8080:8080 spring-boot-app
This will start the Spring Boot application in the container and map port 8080 on your host machine to port 8080 in the container.
Conclusion
With the above Dockerfile, you can easily containerize your Spring Boot application and run it in any environment that supports Docker. This approach allows you to package your app and its dependencies, ensuring consistency across different environments.
For more advanced configurations, consider integrating with Docker Compose for multi-container setups (e.g., connecting to a database) or using multi-stage builds to optimize the image size.