Do you want to move your cloud-native Spring Boot application into a Docker image and test its functionality as it runs within a container? If you have limited exposure with the development and deployment of 12-factor apps, this sounds like an intimidating prospect. But, don't fret.
TheServerSide has published several articles on how to create Spring Boot applications, be it mobile, MVC-based applications or simply RESTful web services. There is a complete, cloud-native application developed with Spring Boot that combines these Spring APIs into a single and fun rock-paper-scissors application. We will use this to demonstrate the deployment of an example Spring Boot application to Docker.
Spring Boot Docker example prerequisites
For this tutorial, you will need to have a Linux distribution -- such as Ubuntu -- with the following parameters:
- A JDK installation
- A Git installation
- A Maven installation
- A Docker installation
Git pull and Maven build
You can obtain the application with the following pull request on the GitHub repository:
[email protected]:~example/$ git clone http://github.com/cameronmcnz/spock-lizard-docker.git
This code will place the source code on your local machine. You will require a Maven build command to generate the executable JAR file which contains the Spring Boot application packaged within an embedded Tomcat container.
Next, move into the target folder of the application and issue the java -jar command to run the application:
[email protected]:~example/spock-lizard-docker/target$ java -jar spock-lizard-1.0.jar
After this command completes, you can play the game by pointing your browser at http://localhost:8080.
Spring Boot and Docker packages
When you're finished with the application, close the terminal window which launched the JVM.
Since this application has a file named Dockerfile in the root directory, you can tell Docker to create a container image with the following command. But, remember to include the '.' at the end, because it will fail to run if you forget.
[email protected]:~/spock-lizard-docker/$ sudo docker build -t spock-lizard-cameron .
I intentionally changed the last word of the image from 'docker' to 'cameron' in the above command just to demonstrate that the name of the Docker image isn't tied to the application it contains.
Run the Spring Boot Docker example
The next step is to run the application within the newly created container image by issuing the following command:
[email protected]:~/spock-lizard-docker/$ sudo docker run -p 8099:8080 -t spock-lizard-cameron
The -p 8099:8080 switch is simply a port mapping that allows external requests that come in on port 8066 to be mapped to the internal port 8080, through which the actual application runs. When you run the app through the container, the port 8099 needs to be specified as part of the URL.
That's all there is to perform a deployment with the Spring Boot Docker example application.