Spring Boot and Docker

Spring Framework is a popular, open source, enterprise-level framework for creating standalone, production-grade applications that run on the JVM.

Spring Boot is a tool that makes developing web application and microservices with Spring Framework faster and easier through three core capabilities:

  • Autoconfiguration
  • An opinionated approach to configuration
  • The ability to create standalone applications

We’ll do following in this article:

  • Create a Spring Boot project.
  • Create a Dockerfile.
  • Create a Docker Hub account and install Docker Desktop for Windows.
  • Create a local image for Docker.
  • Push image to Docker Hub.
  • Pull image from Docker Hub and run.

Note: You can download all the source code of the project from https://github.com/umutdogan/spring-boot-demo.

Create a Spring Boot Project

  1. Open IntelliJ IDEA and click New Project button.
  2. Select Spring Initialzr from the list and fill in the properties as follows and click Next:
    • Name: spring-boot-demo
    • Location: C:\Projects\spring-boot-demo (or any preferred folder location)
    • Language: Java
    • Type: Maven
    • Group: com.umutdogan.java
    • Artifact: spring-boot-demo
    • Package Name: com.umutdogan.java.springbootdemo
    • Project SDK: 11
    • Java: 11
    • Packaging: Jar
  3. Select Spring Boot version as 2.6.3 (or latest stable version) and add following dependencies by searching and clicking the checkboxes next to them.
    • Spring Web
    • Spring Boot Actuator
    • Spring Boot DevTools
  4. Click Finish button.
  5. Edit pom.xml file and add following before </build> tag.
     <finalName>spring-boot-demo</finalName>
    
  6. Create a new package named controller under com.umutdogan.springbootdemo package.
  7. Create a new class named DemoController under com.umutdogan.springbootdemo.controller package with following content.
     package com.umutdogan.java.springbootdemo.controller;
        
     import org.springframework.web.bind.annotation.GetMapping;
     import org.springframework.web.bind.annotation.RestController;
        
     @RestController
     public class DemoController {
        
         @GetMapping("/hello")
         public String sayHello() {
             return "Hello World!";
         }
     }
    
  8. Run the Spring Boot application named SpringBootDemoApplication by clicking the run icon at top right section of the IntelliJ IDEA.
  9. If the application is built successfully you should see some message like Completed initialization in 1 ms in Console.
  10. Open Chrome and go to http://localhost:8080/hello and it should display Hello World! message.

Create a Dockerfile

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build users can create an automated build that executes several command-line instructions in succession.

  1. Go to the root of the project and click Create -> New -> File and name the file as Dockerfile.
  2. Type following into the newly created file.
     FROM adoptopenjdk/openjdk11:latest
        
     EXPOSE 8080
        
     ADD target/spring-boot-demo.jar spring-boot-demo.jar
        
     ENTRYPOINT ["java", "-jar", "spring-boot-demo.jar"]
    
  3. Run clean package from the Maven menu and make sure you don’t get any error messages.

Create a Docker Hub Account and Install Docker Desktop for Windows

  1. Go to https://hub.docker.com and create a Docker Hub account. Free Tier is enough for our basic implementations. You can upgrade if needed.
  2. Download Docker Desktop for Windows from https://docs.docker.com/desktop/windows/install/ and install.

Create a Local Image for Docker

  1. Using PowerShell, go into the project root folder (e.g. C:\Projects\spring-boot-demo) and type docker login.
  2. Type docker build -t spring-boot-demo . to build the docker project.
  3. Type docker images to see if the image is shown in local repository. You should see something like below:
     REPOSITORY         TAG       IMAGE ID       CREATED              SIZE
     spring-boot-demo   latest    de106b49f97d   About a minute ago   457MB
    

Push Image to Docker Hub

  1. Tag the image with our username in Docker Hub: docker tag spring-boot-demo udogan/spring-boot-demo.
  2. Now, if you type docker images you’ll see something like below:
     REPOSITORY                TAG       IMAGE ID       CREATED         SIZE
     spring-boot-demo          latest    de106b49f97d   7 minutes ago   457MB
     udogan/spring-boot-demo   latest    de106b49f97d   7 minutes ago   457MB
    
  3. Now push the image to Docker Hub: docker push udogan/spring-boot-demo.
  4. If you check the Docker Hub repository, you can see the image is pushed to remote successfully.

Pull Image from Docker Hub and Run

  1. Before pulling images from Docker Hub, let’s remove the local images first to see it pulls the images correctly from remote: docker rmi spring-boot-demo udogan/spring-boot-demo
  2. Now if you run docker images, you won’t see above two images.
  3. To pull the remote image from Docker Hub and run, you need to type following command: docker run -p 8080:8080 udogan/spring-boot-demo.
  4. You’ll see following messages in PowerShell screen:
     Unable to find image 'udogan/spring-boot-demo:latest' locally
     latest: Pulling from udogan/spring-boot-demo
     08c01a0ec47e: Already exists
     eff343e8fe14: Already exists
     14102102fd1e: Already exists
     4222f1ed4d7b: Already exists
     Digest: sha256:69b12f19e91125b8a64d70a2673c687d0514d96bab1a58ff553e6f89836f7ef6
     Status: Downloaded newer image for udogan/spring-boot-demo:latest
        
       .   ____          _            __ _ _
      /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
     ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
      \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
       '  |____| .__|_| |_|_| |_\__, | / / / /
      =========|_|==============|___/=/_/_/_/
      :: Spring Boot ::                (v2.6.3)
        
     2022-02-13 16:01:25.270  INFO 1 --- [           main] c.u.j.s.SpringBootDemoApplication        : Starting SpringBootDemoApplication v0.0.1-SNAPSHOT using Java 11.0.14.1 on 67d919c04363 with PID 1 (/spring-boot-demo.jar started by root in /)2022-02-13 16:01:25.272  INFO 1 --- [           main] c.u.j.s.SpringBootDemoApplication        : No active profile set, falling back to default profiles: default
     2022-02-13 16:01:26.935  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
     2022-02-13 16:01:26.956  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
     2022-02-13 16:01:26.956  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
     2022-02-13 16:01:27.016  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
     2022-02-13 16:01:27.017  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1641 ms
     2022-02-13 16:01:27.741  INFO 1 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
     2022-02-13 16:01:27.790  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
     2022-02-13 16:01:27.811  INFO 1 --- [           main] c.u.j.s.SpringBootDemoApplication        : Started SpringBootDemoApplication in 3.245 seconds (JVM running for 3.8)
    
  5. If you go to http://localhost:8080/hello from your Chrome browser, you’ll see the Hello World! message in the screen.
  6. You can exit or close the session to terminate the program.
  7. This was a basic deployment that displays a simple Hello World! message using Spring Boot.
References:
  1. https://spring.io/projects/spring-boot
  2. https://www.ibm.com/cloud/learn/java-spring-boot
  3. https://www.youtube.com/watch?v=SzbeDqBSRkc
  4. https://docs.docker.com