Who this tutorial is for
This tutorial is for anyone who is wondering how to take a Spring Boot 2 application and containerize it with Docker.
Prerequisites
Before you begin, either make sure you have an existing Spring Boot 2 application, or if you don’t, I recommend going through the Spring Guide “Building a RESTful web service” with Spring Boot.
Once you have that, return here.
Video Version
As an added bonus, check out the end of this tutorial, where I’ve placed a video version of all of this.
Step 1. Add a Dockerfile
First, add a text file to the root directory of your application named “Dockerfile.”
Copy and paste the following into it:
FROM openjdk:11ARG JAR_FILE=target/*.jarCOPY ${JAR_FILE} app.jarENTRYPOINT ["java","-jar","/app.jar"]FROM openjdk:11 ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","/app.jar"]FROM openjdk:11 ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","/app.jar"]
Enter fullscreen mode Exit fullscreen mode
NOTE: if you are using Java 8, or another version of Java, be sure to select the correct base for your image in the “FROM” line (line 1). You can find other openjdk container bases at Docker Hub.
You may also be happy to know that there’s a Spring Guide titled “Spring Boot with Docker” where you can find more information about Dockerfiles and Spring Boot.
Step 2. Build an image
Next, you will build an image. Open a terminal, navigate to the root directory of your application, and type:
docker build -t {tag}docker build -t {tag}docker build -t {tag}
Enter fullscreen mode Exit fullscreen mode
You can read more about tags in the Docker documentation.
If you plan to use Docker Hub, then it’s common to use your Docker Hub username. For example, I used this command on my example:
docker build -t scottashipp/helloworlddocker build -t scottashipp/helloworlddocker build -t scottashipp/helloworld
Enter fullscreen mode Exit fullscreen mode
Step 3. Create and run a container
Now that you have built an image, you can create and run a container from that image.
In the same directory, type:
docker run -p 8080:8080 {tag}docker run -p 8080:8080 {tag}docker run -p 8080:8080 {tag}
Enter fullscreen mode Exit fullscreen mode
If you forgot how you tagged your image, try listing images:
docker image lsdocker image lsdocker image ls
Enter fullscreen mode Exit fullscreen mode
Assuming you find your tag, and run it correctly (for example I used “docker run -p 8080:8080 scottashipp/helloworld”), you should see Spring Boot start up, and the familiar “Started application . . .” message.
In this tutorial
In this tutorial, you have:
- Built and tagged a Docker image from an existing Spring Boot application
- Created and ran a Docker container from the created image
Next Steps
Next, check out the video version! Make sure to like and subscribe!
暂无评论内容