Springboot application with Docker
Tags: springboot, docker
Published: 2020-04-09 08:55:20

---
title: Springboot application with Docker
published: true
date: 2020-03-07 01:50:00 UTC
tags: Spring Boot, Docker
canonical_url: 
---

[![](https://1.bp.blogspot.com/-XdY3CtcgFIs/XmLzRRt6WiI/AAAAAAAAAL8/Bu2jgMgS9qg4PXmX_ojJPQYbutqehCi0wCLcBGAsYHQ/s640/pjimage.jpg)](https://1.bp.blogspot.com/-XdY3CtcgFIs/XmLzRRt6WiI/AAAAAAAAAL8/Bu2jgMgS9qg4PXmX_ojJPQYbutqehCi0wCLcBGAsYHQ/s1600/pjimage.jpg)
  

<input id="lsid" type="hidden" value="700111">   

## Table of Content

- [Technology Used](#1_LIS)
- [Code Structure](#2_H2)
- [Building Docker Image](#8_H3)
- [Github Source Code](#12_GIT)

## 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

```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

```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

```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] (https://github.com/bootng/springboot_docker)

- git clone https://github.com/bootng/springboot\_docker.git
- cd springboot\_docker
- mvn install
- docker build . - t springboot\_docker
- docker run -p 8080:8080 springboot\_docker