If you don't have an application already, create one using Spring Initializr (https://start.spring.io/).
Generate a basic Maven or Gradle project with dependencies you need (for example, Spring Web).
In the root directory of your Spring Boot application, create a new file named Dockerfile (no extension).
# Use an official JDK runtime as a parent image FROM openjdk:17-jdk-slim # Add a label to identify the application LABEL maintainer="your-email@example.com" # Set the working directory in the container WORKDIR /app # Copy the application JAR file to the container COPY target/your-application-name.jar app.jar # Expose the port your app runs on EXPOSE 8080 # Run the application ENTRYPOINT ["java", "-jar", "app.jar"]
Note: Replace your-application-name.jar with the actual name of your Spring Boot JAR file.
In the terminal, navigate to the root directory of your Spring Boot project, then run:
./mvnw clean package
This will build the application and generate a JAR file in the target/ directory.
Run the following command in the terminal from the root of your project (where the Dockerfile is located):
docker build -t my-spring-boot-app .
Here:
Now that the image is created, you can run the container:
docker run -p 8080:8080 my-spring-boot-app
Explanation:
Your Spring Boot application should now be accessible on http://localhost:8080.
Open a browser or use a tool like curl to access the application and verify it's working:
curl http://localhost:8080
docker stop <container-id>
docker system prune
This approach should give you a clear path to Dockerizing your Spring Boot application!
The above is the detailed content of Dockerizing a Spring Boot Application For Beginners. For more information, please follow other related articles on the PHP Chinese website!