DEV Community

Sidd B
Sidd B

Posted on • Originally published at bootng.com on

Springboot application with Docker

Table of Content

Docker and Spring boot Application

This blog details the steps taken to add docker support to a spring boot application written in java.

This blog is developed with

  • Java 11
  • Docker 19.03.5
  • Spring Boot 1.5.9
  • Maven

The spring boot application is a simple application to read all the links from a target URL and rendering the links.

Code Structure

SpringBootLinkApplication.java

@ComponentScan({"com.bootng"}) 
@SpringBootApplicationpublic class SpringBootLinkApplication {
 private static final Logger log = LoggerFactory.getLogger(SpringBootLinkApplication.class);
 public static void main(String args[]) {
  log.debug("about to call SpringBootLinkApplication.run()");
  SpringApplication.run(SpringBootLinkApplication.class, args);
 }
 @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
  return args -> {
   log.info("Let's inspect the beans provided by Spring Boot:");String[] beanNames = ctx.getBeanDefinitionNames();Arrays.sort(beanNames);
   for (String beanName: beanNames) {
    log.info(beanName);
   }
  };
 }
}

LinkController.java

@Controllerpublic class LinkController {
 private static final Logger log = LoggerFactory.getLogger(SpringBootLinkApplication.class);
 @Autowired BlogService blogService;
 @RequestMapping(value = {
  "/"
 }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Object getHome() {
  log.info("inside getHome ");
  return "GoTo \\links to see all the links \n";
 }
 @RequestMapping(value = {
  "/links"
 }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Object getHeadLines() {
  log.info("inside blog GET getHeadLines method");
  String sourceLink = "http://www.bootng.com";
  List < String > links = blogService.getAllLinks(sourceLink);
  StringBuilder result = new StringBuilder();
  for (String link: links) {
   result.append(link).append("\n");
  }
  return "Links scanned from bootng.com \n" + result;
 }
 public @ResponseBody Object getHeadLines(@RequestParam String sourceLink) {
  log.info("inside blog GET getHeadLines method");
  List < String > links = blogService.getAllLinks(sourceLink);
  StringBuilder result = new StringBuilder();
  for (String link: links) {
   result.append(link).append("\n");
  }
  return "Links scanned from specified url \n" + result;
 }
 @RequestMapping(value = {
  "/test"
 }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Object isSerivceUp() {
  log.info("inside blog GET method");
  return "Service is Running Fine";
 }
}

BlogLinkService.java

@Servicepublic class BlogLinkService {
 public List < String > getAllLinks(String url) {
   List < String > result = new ArrayList < String > ();
   Document doc;
   try {
    doc = Jsoup.connect(url).get();
    Elements links = doc.select("a[href]");
    for (Element link: links) {
     result.add(String.format(" %s : %s", link.attr("abs:href"), link.text()));
    }
   } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }}

The above files are part of the main Java Classes for the Springboot application. Which defines the Application, Controller, and Service Class. Now we will add docker support to it. For that we need to add a file with name "DockerFile" to the repository as follows.

DockerFile

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.war

#cd /usr/local/workspace
WORKDIR /usr/local/workspace

COPY ${JAR_FILE} app.jar

# java -jar /usr/local/workspace/app.jar
ENTRYPOINT ["java","-jar","app.jar"]

Building Docker Image

Build Project and Build Docker Image

Following commands will first build our Spring Boot application generate a war file, and then build the docker image containing the war file

mvn install
docker build . -t springboot_docker
Sending build context to Docker daemon  43.16MB
Step 1/5 : FROM openjdk:8-jdk-alpine
 ---> a3562aa0b991
Step 2/5 : ARG JAR_FILE=target/*.war
 ---> Using cache
 ---> e637fbb1ac39
Step 3/5 : WORKDIR /usr/local/workspace
 ---> Using cache
 ---> daa4b4a89727
Step 4/5 : COPY ${JAR_FILE} app.jar
 ---> Using cache
 ---> bd3788117296
Step 5/5 : ENTRYPOINT ["java","-jar","app.jar"]
 ---> Using cache
 ---> 118546685007
Successfully built 118546685007
Successfully tagged springboot_docker:latest

Execute the SpringBoot application inside the docker image with tag "springboot_docker"

Previous step we build the docker image containing our Spring boot applicaiton and tagged the docker image with tag "springboot_docker". To run the dockerized application run the following command.

docker run -p 8080:8080 springboot_docker
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.9.RELEASE)
 INFO main c.b.SpringBootLinkApplication:57 - Started SpringBootLinkApplication in 4.813 seconds

Access the Application

Since the Spring boot web application is running on port 8080, open a browser and go to http://localhost:8080/links?sourceLink=http://bootng.com. It should print links somewhat like bellow

 Links scanned from bootng.com 
 https://www.bootng.com/search/label/spring-boot?max-results=3 : spring-boot
 https://www.bootng.com/search/label/gcp?max-results=3 : GCP
 https://www.bootng.com/search/label/angular?max-results=3 : Angular
 https://www.bootng.com/search/label/Agile?max-results=3 : Agile
 https://www.bootng.com/search/label/Java?max-results=3 : Java
 https://www.bootng.com/search/label/Java?max-results=3 : Links

Download Source code Repo

Top comments (0)