编程知识 cdmana.com

Practice of deploying spring boot microservices on kubernetes

 stay Kubernetes Upper Department Spring Boot Microservice practice

Although this article discusses Spring Boot Applications , But the concepts discussed apply to any Microservices Applications .

You want to know how to Kubernetes Is there a micro service ?Kubernetes Is the most popular choice for running microservice applications ?

Let's get started :

What is? Kubernetes?

Kubernetes Allow us to 、 Deploying containerized microservice applications in a private or hybrid cloud infrastructure .Kubernetes Is an open source container orchestration platform .Kubernetes Some of the important features of are :

  • Auto expand and rollback
  • Service discovery
  • self-healing
  • Scale horizontally

What is a container ?

A container is an executable that packages code and all its dependencies in a standard unit . therefore , Container applications can run quickly and reliably from one computing environment to another .Kubernetes Some of the container runtimes supported on are Docker、containerd and CRI-O.

In this paper , I will use Docker When running as a container . You can check the installation in the official documentation Docker Explanation .

Create containers for microservices

Assume that... Is installed Docker, The next step is to build the container image . So , We will use Dockerfile.

Docker A file is a text file , Include as Docker Description of container setting environment .Docker Can be read through Docker The description in the file automatically generates an image .

for example ,product catalog microservice Of Dockerfile yes :

FROM openjdk:11-jre-slimRUN mkdir /appWORKDIR /appADD ./build/libs/product-catalog-svc-0.0.1.jar /app/app.jarEXPOSE 8080ENTRYPOINT ["java", "-jar", "app.jar"]
  • FROM The directive defines the base image as openjdk:11 jre slim.
  • RUN The instruction creates a file named app The new directory .
  • WORKDIR The instruction is the next ADD Directive to set the working directory .
  • ADD Directive adds the contents of the build directory to the /app Catalog .
  • EXPOSE Instructions Docker The container listens on a specific port at run time .
  • ENTRYPOINT Instructions tell Docker Which command to run at startup .

From you to Dockerfile Building container images , We need to follow the following steps .

1. establish Spring Boot jar

To build SpringBoot jar, Please from the root directory product catalog svc Run the command gradlew clean build. This command packages all classes and dependencies into one jar in . This is from Spring Boot Of Gradle Plug in implementation , The plug-in is defined as :

plugins {	id 'org.springframework.boot' version '2.5.3'}

To verify , Please from the root directory product catalog svc Run the command java-jar build/libs/product-catalog-svc-0.0.1.jar. This will be on the port 8080 Launch the product catalog on microservice. You can go to Postman Medium test API.

2. establish Docker Mirror image

To create a docker Mirror image , Please run the command docker build-tproduct-catalog:1.0.0 from product-catalog-svc In the directory 1.0.0. This command creates a file marked 1.0.0 Of Docker image Product catalog . You can run the command docker image ls To verify that the image was successfully created . This shows the following output :

REPOSITORY          TAG       IMAGE ID       CREATED         SIZEproduct-catalog     1.0.0     1b3edac07100   9 minutes ago   261MB

perhaps , If you want to verify that the image can run successfully , Please run the command docker run-p 8080:8080 product catalog:1.0.0. You should see a SpringBoot The application is starting . If you like , You can connect to localhost:8080 adopt Postman To test .

3. take Docker Publish container to Docker Hub

Container registry ( Such as Docker Hub) Allows you to share container images with others . First , You need to Docker Hub Create an account . stay Docker Hub After you create a repository in your account , Local images can be pushed to this repository . You can go to Docker Hub Find complete instructions for creating a repository and pushing images to the repository on .

To push the image to Docker Hub, First , We have to use Docker Hub The repository techdozo/product catalog svc Mark local techdozo/product-catalog-svc. This can be done by running the following command :

docker tag product-catalog:1.0.0 techdozo/product-catalog-svc:1.0.0

After marking the mirror , We can push the image as follows :

docker push techdozo/product-catalog-svc:1.0.0

Microservice deployment architecture

In this paper , We will be here Kubernetes Deploy the product catalog microservice on the cluster . Although this article introduces local deployment , But it's best to understand how microservices are deployed in a production environment .

Microservice applications in Kubernetes The reference deployment on is as follows :

 stay Kubernetes Upper Department Spring Boot Microservice practice

The deployment consists of the following components .

Kubernetes Cluster

To be in Kubernetes Up operation microservices Applications , You need a Kubernetes colony . You can choose Kubernetes Cluster as a hosted service , for example ,AKS、GKE、Amazon EKS. Besides , You can also install kubeadm、kubespray etc. . For local machines , You can install Kind、Minikub etc. .

Ingress

Entrance will HTTP(S) route ( It's called the entrance ) Open as RESTfulWebAPI. for example , Entry rule path :/products It can be used as RESTFul API/ Products in the Kubernetes Access outside the cluster . The entry controller is responsible for executing entry rules .

Load balancer

The load balancer will be common internet Traffic is routed to the portal . It is configured with a common interface for the entry controller IP.DNS Can be mapped to the public address of the load balancer IP. This allows API Consumer use DNS call API, for example ——https://example.com/products.

database

Almost every application needs a database . In cloud deployment , You can choose to host the database . Besides , You can also choose to self manage the database .

Utility services and observability stack

In addition to application services , You can also run other utility services . for example , Container security applications ( Such as Twistlock)、 cache ( Such as Redis) etc. .

Observability includes measurement 、 Tracking and logging . The observability stack helps you collect and store metrics 、 Logging and application telemetry . You can choose the observability stack of cloud management . perhaps , You can use self managed observability tools . for example , You can use Elasticsearch Store application logs , Use Prometheus Store application metrics , Use Grafana Visualizing , Use OpenTelemetry Tracking , wait .

Container registry

The container registry helps you store information that can be deployed in Kubernetes Private container image on cluster . Most cloud providers have their own container registry .

CI/CD pipeline

CI/CD The Conduit ( Such as Jenkins The Conduit ) Helps you automate build and deploy .

Helm

Helm yes Kubernetes Software package manager. It will Kubernetes Objects are bundled into a that can be deployed 、 In the unit of version control and update .

Run local cluster

Look at the microservice After the reference production deployment , Let's see what a local deployment looks like . The main difference is that there is no need to configure a load balancer and perform DNS mapping , The remaining steps remain unchanged .

It's local Kubernetes Run the product catalog on the cluster microservice, have access to Kind.

To create a cluster , Please save the following code in kind-config.yaml in , And run the command kind create cluster--config kind-config.yaml.

apiVersion: kind.x-k8s.io/v1alpha4kind: Clusternodes:  - role: control-plane    kubeadmConfigPatches:      - |        kind: InitConfiguration        nodeRegistration:          kubeletExtraArgs:            node-labels: "ingress-ready=true"    extraPortMappings:      - containerPort: 80        hostPort: 81        protocol: TCP      - containerPort: 443        hostPort: 443        protocol: TCP  - role: worker  - role: worker

You can run the command kind get clusters To verify kind Cluster deployment . This command returns the default cluster name and type .

Local microservice deployment

At least , To deploy microservices and expose RESTfulWebAPI, You need to know three Kubernetes Concept . These are :

  • Deploy : Enables you to create POD Copy of .
  • service :Kubernetes Components , Allow you access to pods.
  • entrance : Through the service will web request ( for example ,/products) Mapping to POD.

Our application is local Kubernetes The deployment architecture in the cluster is as follows :

 stay Kubernetes Upper Department Spring Boot Microservice practice

Let's take a closer look at these components .

Deploy

Release Docker After mirroring , Can be in Kubernetes In order to pod Run the image as .POD Yes, we can Kubernetes The smallest deployable cell created and managed in .Pod Contains one or more containers , It contains shared storage and network resources and specifications for running containers . However , Most of the time , You will not directly create pod, Instead, it is created through a higher-level construct called deployment pod.

Kubernetes Deployment is a higher-level object , It allows you to POD Provide declarative updates .

What does a declarative update mean ?

Kubernetes Objects can be configured by storing object configuration files in a directory (YAML Inventory file ) To create and update . then , You can use the command kubectl apply, Create and update these objects recursively as needed .

contrary , In imperative methods , You feed the command directly to Kubernetes. for example , To create a nginx Deployment of , Please run the command kubectl create deployment nginx--image nginx.

Use deployment , You can achieve :

  • Rollout a RelicaSet: When creating a deployment ,Kubernetes A copy set and the required number of copies will be created internally POD.POD You can use deployment ( Rolling update strategy ) Launch... In a predictable manner . This ensures that all users of the application will not experience downtime . The deployment policy consists of fields spec.strategy.type Definition , It may be worth RollingUpdate, The default value is RollingUpdate
  • Roll back early deployment : If the current deployment is unstable , Can be restored to an earlier version of the deployment .
  • Pod to update : If your application has a new version (Pod A new version of the ), Deployment will create a new replication set , And in a controlled manner Pod Move from the old replica set to the new replica set .
  • Expand deployment : You can extend the Kubernetes Deploy to create additional pods to handle loads .

To create a deployment , Please save the following code in YAML In file , such as deployment.YAML, And then run the command kubectl apply-f deployment.yaml

apiVersion: apps/v1kind: Deploymentmetadata:  name: product-catalog  labels:    app: product-catalogspec:  replicas: 3  selector:    matchLabels:      app: product-catalog  template:    metadata:      labels:        app: product-catalog    spec:      containers:        - name: product-catalog          imagePullPolicy: IfNotPresent          image: techdozo/product-catalog-svc:1.0.0

The above command creates a Kubernetes Deploy , It contains three and tags app:product catalog Matching pod copy . After running the above command ,Kubernetes from DockerHub Extract from the repository Docker image techdozo/product catalog svc:1.0.0 And create POD.

To verify , Please run the command kubectl get pods. You should see the following :

NAME                               READY   STATUS    RESTARTS   AGEproduct-catalog-5fcb6cc8fb-6b45b   1/1     Running   0          43sproduct-catalog-5fcb6cc8fb-fp6dk   1/1     Running   0          43sproduct-catalog-5fcb6cc8fb-hdmf7   1/1     Running   0          43s

service

stay Kubernetes,pods It's short-lived . Create and destroy POD To match the replica defined in the deployment . Every pod All have their own IP Address , But this IP The address is not permanent .

This leads to a problem : If a group POD( such as order microservice) Need to work with other POD( such as product microservice) signal communication ,order microservice How to track product microservice Of IP Address ? This is it. Kubernetes Where services can be used .

Kubernetes Service is an abstraction , It defines a set of logic POD( Usually determined by the selector ) And access to them .

Service type

Kubernetes There are four types of services :

1. ClusterIP( Default ): Service type ClusterIP Expose the internal of the cluster IP Service on . This service can only be accessed in a cluster . This is a Kubernetes It's the most common method in .

2. NodePort:NodePort At each node of the static port IP Go public .NodePort Use <NodeIP>:<NodePort> Accessing services from outside the cluster .

3. LoadBalancer: The service creates an external load balancer in the cloud ( Such as Google cloud、Azure), And assign a fixed external IP. When you want direct access to services ( for example , From an external cluster ) when , This is the most commonly used .

4. ExternalName: This type of service maps services to ExternalName The contents of the field . When you want to access external resources ( for example , External databases that do not belong to the cluster ) when , This is very useful .

List of services

You can add the product catalog to the microservice Kubernetes Services are defined as :

apiVersion: v1kind: Servicemetadata:  name: product-catalogspec:  type: ClusterIP  selector:    app: product-catalog  ports:    - port: 80      targetPort: 8080

targetPort It's a catalogue microservice Docker The port exposed by the container , This port is the service port itself .

To create a Kubernetes service , Please be there. service.yaml Copy the above definition , And run the command kubectl apply-f service.yaml.

To verify , Please run the command kubectl get service, The command outputs the following :

NAME              TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGEkubernetes        ClusterIP   10.96.0.1      <none>        443/TCP   15mproduct-catalog   ClusterIP   10.96.19.115   <none>        80/TCP    19s

Ingress

In short , The portal exposes services from outside the cluster to inside the cluster HTTP(S) route , Such as /products. You can go to Ingress Define traffic routing rules in resources . It is the responsibility of the entrance controller to comply with the entrance rules . please remember ,Kubernetes There is no built-in standard entry controller , Therefore, a compatible entry controller must be installed .

Ingress Resource

You can put the product catalog microservice The entry of is defined as :

apiVersion: networking.k8s.io/v1kind: Ingressmetadata:  name: app-ingressspec:  rules:    - http:        paths:          - path: /products            pathType: Prefix            backend:              service:                name: product-catalog                port:                  number: 80

The entry rule contains the following information :

  • host ( Optional ): If no host is specified , Then the rule applies to all inbound HTTP Traffic . If a host is provided ( for example example.com), Then the rule applies to that particular host .
  • route : The path has an associated backend defined using the service name and port . If the host and path match , The portal controller redirects traffic to the reference service .

To create an entry , Please be there. ingres.yaml Copy the above entry definition , And run the command kubectl apply-f ingres.yaml

To verify the entry , Please run the command kubectl get ingres.

NAME          CLASS    HOSTS   ADDRESS   PORTS   AGEapp-ingress   <none>   *                 80      10s

Ingress Controller

Kubernetes The entry controller is responsible for executing entry rules . To create an entry controller , Please follow “ Introduction to species : Quick start multi node local Kubernetes to cluster around ” The steps mentioned in .

install ingress controller after , If run again kubectl get ingress command , You can see that the assignment is localhost The address of .

NAME          CLASS    HOSTS   ADDRESS     PORTS   AGEapp-ingress   <none>   *       localhost   80      13m

Use Helm Figure for deployment

perhaps , You can use Helm Chart deployment product catalog microservice. You can Github Find (https://github.com/techdozo/microservices/tree/master/product-catalog-svc/kubernetes/helm/product-catalog)

Before installing the chart , You can run the test run as follows :

helm install product-catalog kubernetes\helm\product-catalog --dry-run

If the run fails , You may have to remove the legacy deployment 、 Service and entrance . You can run the command kubectl delete<resource> To achieve this . for example , To delete a service , You can run commands kubectl delete service/product catalog.

Once you are satisfied with the commissioning , You can install the chart by running the following command :

helm install product-catalog kubernetes\helm\product-catalog

The test application

After application deployment , Can be in Postman Test the application in . So , You need to baseUrl Change the variable to point to port 81, As shown below :

 stay Kubernetes Upper Department Spring Boot Microservice practice

summary

Kubernetes Is an open source container orchestration platform , It allows us to 、 Deploying containerized microservice applications in a private or hybrid cloud infrastructure .

To be in Kubernetes Deployment in China Spring Boot microservice Applications , We need to :

  • by microservice Create a Spring Boot jar.
  • Use the application jar establish Docker Mirror image .
  • Definition Kubernetes Deploy , Indicate the number of copies of the application .
  • Define a service , The service defines access POD The rules of .
  • Define an entry , Through the service will web request ( for example ,/products) Mapping to POD.

Original address :https://techdozo.dev/deploying-a-restful-spring-boot-microservice-on-kubernetes/

版权声明
本文为[Old K's Java blog]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145756180q.html

Scroll to Top