public

Spring Boot + Docker on Kubernetes, from scratch

Create a RESTful API Service with Spring Boot, dockerize & deploy to Kubernetes We’ll first create a new Spring Boot Application [https://github.com/mateothegreat/k8-byexamples-spring-rest] implementing a basic

Latest Post Speed kills software engineering. by Matthew Davis public

Create a RESTful API Service with Spring Boot, dockerize & deploy to Kubernetes

Spring Boot on Kubernetes

We’ll first create a new Spring Boot Application implementing a basic HTTP GET service endpoint. Once our application is up and running we can go ahead and create a docker image and launch a docker container to test our service out. And finally, we’ll take our docker image and deploy it to a Kubernetes Cluster for a production grade deployment.

Dockerfile

We use the stock jre image from openjdk to run our application inside of:

FROM openjdk:8-jre-alpine

COPY build/libs/k8-byexamples-spring-rest-0.0.1-SNAPSHOT.jar /application.jar

CMD ["java", "-jar", "/application.jar"]

Makefile (optional)

I’ve created a simple Makefile to speed things up. Simply make all to build & push the docker image. Similarly you can make k8/install to install the kubernetes manifests:

VERSION ?= $(shell git rev-parse HEAD)
APP     ?= k8-byexamples-spring-rest
IMAGE   ?= gcr.io/matthewdavis-byexamples/$(APP):$(VERSION)

.PHONY: build

all: build push

build:

   docker build -t $(IMAGE) .

run:

   docker run -p 8080:8080 $(IMAGE)

push:

   docker push $(IMAGE)

k8/install:

   kubectl apply -f manifests/

k8/delete:

   kubectl delete -f manifests/

TestRestController.java

This is a simple REST controller that responds to HTTP POST requests (i.e.: https:///test/echo):

package com.example.k8byexamplesspringrest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestRestController {

    @PostMapping("/echo")
    public ResponseEntity<?> testResponse(@RequestBody String body) {

        return new ResponseEntity<>("You said: " + body, HttpStatus.OK);

    }

}

Source Code Repositories:

Matthew Davis

Published 4 years ago