Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot 2.0 Microservice Deployment to Google Cloud Kubernetes Engine With Docker

DZone's Guide to

Spring Boot 2.0 Microservice Deployment to Google Cloud Kubernetes Engine With Docker

This tutorial will show you the steps and the source code to create a Spring Boot microservice application and deploy it to the Google Cloud Platform Kubernetes Engine.

Free Resource

Containerized Microservices require new monitoring. See why a new APM approach is needed to even see containerized applications.

In this article, we are going to create a Spring Boot microservice application and deploy it to the Google Cloud Platform Kubernetes Engine with Docker.

Prerequisites

  1. Google Cloud account with billing enabled.

  2. Google Cloud SDK should be installed on your machine and configured into your Google account.

  3. Kubernetes components should be installed on your Google Cloud SDK.

  4. Docker version 17.12.0

  5. Gradle 4.0 or later

1. Create Spring Boot 2.0 Microservice Application

Generate a Gradle project with Java and Spring Boot version 2.0.0 from http://start.spring.io/. Provide the following Project Metadata artifact coordinates and add the Spring Boot starters dependencies to your application.

Project Metadata Artifact coordinates:

1. Group: com.examples.projects

2. Name: userservice

Spring Boot starter dependencies:

1. Web - To write a Rest APIs.

2. H2 - Embedded database to store and retrieve the user details

3. JDBC - To connect the H2 database by using JDBC Template

gradle project from Spring Initializer

After downloading the project, the Gradle file looks given below.

The build.gradle is given below:

buildscript {
 ext {
  springBootVersion = '2.0.0.RELEASE'
 }
 repositories {
  mavenCentral()
 }
 dependencies {
  classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
 }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example.projects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
 mavenCentral()
}


dependencies {
 compile('org.springframework.boot:spring-boot-starter-jdbc')
 compile('org.springframework.boot:spring-boot-starter-web')
 runtime('com.h2database:h2')
 testCompile('org.springframework.boot:spring-boot-starter-test')
}

The main Spring Boot application class file is given below.

UserserviceApplication.java

package com.example.projects.userservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UserserviceApplication {

 public static void main(String[] args) {
  SpringApplication.run(UserserviceApplication.class, args);
 }
}

Create a schema.sql file and data.sql file under src/main/resources directory to create a schema and insert the default entries into the H2 database. The schema.sql and data.sql file will be executed automatically in memory when the application startup.

schema.sql

CREATE TABLE USERS (ID INT PRIMARY KEY, NAME VARCHAR(45), EMAILID VARCHAR(255));

data.sql

INSERT INTO USERS (ID, NAME, EMAILID) VALUES (1, 'John William','john_william@gmail.com');
INSERT INTO USERS (ID, NAME, EMAILID) VALUES (2, 'Mike Daniel','mike_daniel@yahoo.co.in');
INSERT INTO USERS (ID, NAME, EMAILID) VALUES (3, 'David Lawrance','david_law@gmail.com');

Create a Java model class with the name Users.java and the user attributes such as id, name, and emailid under the package com.example.projects.userservice.model.

Users.java

package com.example.projects.userservice.model;

public class Users {

 private String id;
 private String name;
 private String emailid;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getEmailid() {
  return emailid;
 }

 public void setEmailid(String emailid) {
  this.emailid = emailid;
 }
}

Create a DAO class with the method to fetch the list of users from the database under the package com.example.projects.userservice.dao

UserServiceDAO.java

package com.example.projects.userservice.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.example.projects.userservice.model.Users;

@Repository
public class UserServiceDAO {

 @Autowired
 JdbcTemplate jdbcTemplate;

 public List < Users > getUsersList() {
  String sqlQuery = "SELECT ID, NAME, EMAILID FROM USERS";
  Collection < Map < String, Object >> rows = jdbcTemplate.queryForList(sqlQuery);
  List < Users > usersList = new ArrayList < > ();
  rows.stream().map((row) -> {
   Users user = new Users();
   user.setId(String.valueOf(row.get("ID")));
   user.setName((String) row.get("NAME"));
   user.setEmailid((String) row.get("EMAILID"));
   return user;
  }).forEach((userObj) -> {
   usersList.add(userObj);
  });
  return usersList;
 }
}

Create a Rest Controller class file which contains the GET API to view the list of users under the package com.example.projects.userservice.controller

UserServiceRestController.java

package com.example.projects.userservice.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.projects.userservice.dao.UserServiceDAO;
import com.example.projects.userservice.model.Users;

@RestController
public class UserServiceRestController {

 @Autowired
 UserServiceDAO userServiceDAO;

 @RequestMapping(value="/users", method=RequestMethod.GET)
 public List<Users> getUsersList() {
return userServiceDAO.getUsersList();
 }
}

Change the server.port number to 8000 in application.properties under src/main/resources directory. The default port number 8080.

server.port=8000

2. Create Docker Image of Spring Boot Application

Now go to the build.gradle file then adds the Gradle docker classpath dependency.

 classpath('se.transmode.gradle:gradle-docker:1.2') 

Add apply plugin docker in build.gradle file.

apply plugin: 'docker'

Change version into project.version is 1.0 in build.gradle file

project.version = '1.0'

Add the group name with the format "gcr.io/<gcp-project-name>" - It is very important.

group = 'gcr.io/demoproject-dev'

Create a copyJar task that type is Copy to copy the jar file from build/libs into build/docker directory.

task copyJar(type: Copy) {
    dependsOn   'build'
    from        "build/libs/userservice-${project.version}.jar"
    into        'build/docker'
}

Create a buildDocker task that type is Docker and it depends on copyJar task to create a Docker image application.

task buildDocker(type: Docker, dependsOn: copyJar) {
    baseImage "java:8"
    runCommand("mkdir userservice")
    addFile("userservice-${project.version}.jar","userservice/")
    workingDir("/userservice")
    runCommand("unzip -q userservice-${project.version}.jar")
    entryPoint(["java","-Xms128m","-Xmx1024m","-cp", "/userservice-config:.","org.springframework.boot.loader.JarLauncher"])
}

Now execute the buildDocker task it will create a Docker image on your machine.

Note: Please make sure Docker is running on your machine.

Command to create a Docker image

gradle buildDocker 

After executing above command, Gradle will take few minutes to create a docker image. Finally, you will get the following message on the console window.

Successfully tagged gcr.io/demoproject-dev/userservice:1.0

BUILD SUCCESSFUL in 20m 11s

Then, execute the below command to view the docker images.

docker images

docker images

3. Create Kubernetes Cluster and Push the Docker Image to the Container Registry

Log in to the Google Cloud Console and go the Kubernetes Clusters page then create a new cluster with the name "demoproject-dev-kube-cluster". If you created a cluster already please use that. Otherwise create a new cluster.

Image title

After creating a cluster, click the connect button and get the command to connect the cluster and execute the command into your gcloud sdk.

clusters list

Image title

gcloud container clusters get-credentials demoproject-dev-kube-cluster --zone asia-east1-a --project demoproject-dev

After executing the above command, you can see the below messages on the console.

Fetching cluster endpoint and auth data.

kubeconfig entry generated for demoproject-dev-kube-cluster. 

Now, push the docker image into the Google Cloud Container Registry. Execute the commandgcloud docker -a and get the Short-lived access token for accessing the Google cloud instances.

Then execute the below command on Google SDK to push the docker image into the Container Registry.

gcloud docker -- push gcr.io/demoproject-dev/userservice:1.0 

Pushing docker image to container registry will take few minutes. After pushing, you can see the docker image on the container registry in your Google cloud console.

4. Create a Deployment in Kubernetes

Now, create a deployment to run the docker image by using command line approach.

Syntax:

  kubectl run {deployment_name} --image=gcr.io/$PROJECT_ID/{name}:{tag} --port={port} 

Command to create a deployment in the Kubernetes cluster:

kubectl run userservice --image=gcr.io/demoproject-dev/userservice:1.0 --port=8000 

To view, the deployments execute the command

kubectl get deployments

To view, the list of pods running on the Kubernetes clusters

kubectl get pods

5. Create a Service to Expose the Application to External Traffic

Now, create a service to expose the application to external traffic by using command line approach.

Syntax:

kubectl expose deployment {deployment_name} --type="LoadBalancer"

Command to create a service:

kubectl expose deployment userservice --type="LoadBalancer"

To view the list of services running

kubectl get services

You can view the External IP address of the service you created. By using that external IP address you can access your application.

In my case, the external IP of the user-service application is given below

external_ip

Then access your application by using this External IP - http://35.201.152.42:8000/users

output

Thank you.

Automatically manage containers and microservices with better control and performance using Instana APM. Try it for yourself today.

Topics:
spring boot ,kubernetes ,google cloud platform ,gcp ,docker ,deployment ,microservices

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}