Kubernetes / Linux Note / 运维笔记

Kubernetes (五) SpringCloud Admin 监控调试应用

Einic Yeo · 6月5日 · 2019年 · · · ·

系统环境:

  • Kubernetes 版本:1.14.0
  • SpringBoot 版本:2.1.6.RELEASE
  • SpringBoot Admin 版本:2.1.5
  • Admin 示例代码 Github 地址:https:/版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!/mirrors.infvie.org/blog-example/springcloud/springboot-admin-k8s

背景:

Spring Boot Admin 是一个开源社区项目,用于管理和监控 SpringBoot 应用程序,展示Spring Boot Admin Client 的 Actuator 端点上的一些监控信息。这里要在 Kubernetes 中部署 SpringBoot Admin,由于 Kubernetes 自带服务发现,所以去掉注册中心等,这里需要和 SpringCloud Kubernetes 完成 Kubernetes 下的服务发现。这里将演示 SpringBoot Admin 与 SpringCloud Kubernetes 配合完成监控 Kubernetes 中的 SpringBoot 应用。

一、SrpingBoot Admin 介绍

Spring Boot Admin 是一个开源社区项目,用于管理和监控 SpringBoot 应用程序,展示Spring Boot Admin Client 的 Actuator 端点上的一些监控信息。

它为应用程序提供以下功能:

  • 显示应用健康状况
  • 关注并下载日志文件
  • 查看jvm系统和环境属性
  • 查看Spring Boot配置属性
  • 支持Spring Cloud的postable / env-和/ refresh-endpoint
  • 轻松的日志级管理
  • ……

二、SrpingCloud Kubernetes 介绍

Spring Cloud Kubernetes 提供 Kubernetes 环境下服务发现的 Spring Cloud 通用接口实现。主要目的是促进在 Kubernetes 中运行的 Spring Cloud 和 Spring Boot 应用程序的集成。

这里我们主要用 SpringCloud Kubernetes 来为 SpringBoot Admin 提供 Kubernetes 环境下的服务发现。

三、创建 SpringBoot Admin 应用

创建 SpringBoot Admin 应用,且引入 Spri版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!ngCloud Kubernetes 作为服务发现。

3.1、Maven 引入相关依赖

在 Maven 中引入 “spring-boot-admin-starter-server” 与 “spring-cloud-kubernetes-discovery” 依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>club.infvie</groupId>
    <artifactId>springboot-admin-k8s</artifactId>
    <version>0.0.2</version>
    <name>springboot-admin-k8s</name>
    <description>demo</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--SpringBoot Admin-->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.1.5</version>
        </dependency>
        <!--SpringCloud Kubernetes-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-kubernetes-discovery</artifactId>
            <version>1.0.2.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3.2、配置 application 文件

加上两个参数:

  • spring.cloud.kubernetes.discovery.primaryPortName:
  • spring.cloud.kubernetes.discovery.serviceLabels:
server:
  port: 8080
  
management:
  server:
    port: 8081                          #---指定监控数据端口为8081,避免和 server.port 一致产生风险
  endpoints:
    web:
      exposure:
        include: "*"

spring:
  application:
    name: springboot-admin-k8s
  cloud:
    kubernetes:
      discovery:
        primaryPortName: management     #---按设要监控 Service 的端口名称
        serviceLabels:
          admin: enabled                #---设置要监控 Service 的 Label 标签

3.3、启动类

需要加上四个注解:

  • @SpringBootApplication:开启 SpringBoot 相关注解,会自动配置相关信息。
  • @EnableDiscoveryClient:开启 Spring服务发现机制。
  • @EnableAdminServer:开启 SpringBoot Admin。
  • @EnableScheduling:开启定时任务,不加此注解服务发现不会执行定时刷新。
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableDiscoveryClient
@EnableAdminServer
@EnableScheduling
public class Application {

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

}

四、将 SpringBoot 应用构建 Docker 镜像

将上面创建的 SpringBoot Admin 应用编译成 Docker 镜像。

4.1、版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!执行 Maven 打包

$ mvn clean package

4.2、Dockerfile 文件

FROM openjdk:8u212-b04-jre-slim
VOLUME /tmp
ADD target/*.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JVM_OPTS="-Xss256k -XX:MaxRAMPercentage=80.0 -Duser.timezone=Asia/Shanghai -Djava.security.egd=file:/dev/./urandom"
ENV JAVA_OPTS=""
ENV APP_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JVM_OPTS $JAVA_OPTS -jar /app.jar $APP_OPTS" ]

4.3、编译 Docker 镜像,且推送到仓库

$ docker build -t infvieclub/springboot-admin-k8s:0.0.1 .

4.4、推送到 Docker 仓库

一般推送选择推到到自己私人仓库,为了方便这里使用的是 docker 官方仓库,将其推送到仓库,方便后续 Kubernetes 操作。

$ docker push infvieclub/springboot-admin-k8s:0.0.1

五、部署应用到 Kubernetes

将 SpringBoot Admin 应用部署到 Kubernetes 中,这里提前设置 Kubernetes 部署的 yaml 文件,然后执行 Kubectl 命令将其启动。

5.1、准备应用 yaml 文件

springboot-admin-rbac.yaml

由于 SpringBoot Admin 需要服务发现,所以创意一个 ServiceAccount。注意提前修改角色所属的“namespace”

apiVersion: v1
kind: ServiceAccount
metadata:
  name: springboot-admin-k8s
  namespace: infviecloud
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: springboot-admin-k8s
subjects:
  - kind: ServiceAccount
    name: springboot-admin-k8s
    namespace: infviecloud
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io

springboot-admin-k8s.yaml

注意下面的 Service 注释说明,必须设置对应 Label 和 Port 名称,SpringBoot Admin 会发现带有这些名称的 Service 和 Port。

apiVersion: v1
kind: Service
metadata:
  name: springboot-admin-k8s
  labels:
    app: springboot-admin-k8s
    admin: enabled            #---设置此标签,表示此应用被 Springboot Admin 服务发现
  annotations:
spec:
  type: NodePort              #---通过NodePort方式暴露端口,方便外界访问
  ports:
    - name: server            #---服务端口名,用于访问监控 UI
      nodePort: 30080
      port: 8080             
      targetPort: 8080
    - name: management        #---指定监控端口名,表示此应用被 Springboot Admin 服务发现 
      nodePort: 30081
      port: 8081
      targetPort: 8081
  selector:
    app: springboot-admin-k8s
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: springboot-admin-k8s
  labels:
    app: springboot-admin-k8s
spec:
  replicas: 1
  selector:
    matchLabels:
      app: springboot-admin-k8s
  template:
    metadata:
      labels:
        app: springboot-admin-k8s
    spec:
      serviceAccountName: springboot-admin-k8s
      containers:
      - name: springboot-admin-k8s
        image: infvieclub/springboot-admin-k8s:0.0.1
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
          name: server
        - containerPort: 8081
          name: management
        resources: 
          limits:
            cpu: 1000m
            memory: 512Mi
          requests:
            cpu: 500m
            memory: 256Mi

5.2、在 Kubernetes 创建应用

利用 Kubectl 命令执行 yaml 文件,创建角色和应用部署对象。

  • -n:指定应用创建的 Namespace,应该替换成自己 Kubernetes 集群中的 Namespace 名称

部署 SpringBoot Admin RBAC

$ kubectl apply -f springboot-admin-rbac.yaml -n infviecloud

部署 SpringBoot Admin Deployment

$ kubectl apply -f springboot-admin-k8s.yaml -n infviecloud

5.3、查看已经启动的 SpringBoot Admin 应用

利用 Kubectl 命令查看 Kubernetes 中启动的应用,可以看到 SpringBoot Admin 已经成功启动。

$ kubectl get pods -n infviecloud

NAME                                          READY   STATUS    RESTARTS   AGE
springboot-admin-k8s-54c668b5ff-b9snz         1/1     Running   0          1m

六、进入 SpringBoot Admin 界面查看应用信息

输入 Kubernetes 集群地址和 SpringBoot Admin Service 的 NodePort 端口,http://ClusterIP:30080 访问 Admin 服务,本人地址为:http://192.168.2.11:30080,打开后看到 Admin 的 UI 界面如下:

七、新增示例进行测试

上面的监控的只有一条应用信息,即 SpringBoot Admin 本身,为了测试其它 SpringBoot 应用是否能正确显示在监控看板,这里我们部署一个示例 “Hello-World” 项目。

7.1、创建一个 SpringBoot 项目且 Maven 引入相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>club.infvie</groupId>
    <artifactId>springboot-helloworld</artifactId>
    <version>0.0.1</version>
    <name>springboot-helloworld</name>
    <description>This a project for Spring Boot , use docker build for helm</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    	<!-- SpringBoot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 设置 Actuator 暴露监控数据 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

7.2、配置 application 文件

appl版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!ication.yaml 配置中配置 management 暴露一些监控端口,且设置端口为 8081

spring:
  application:
    name: springboot-helloworld

server:
  port: 8080
  
management:
  server:
    port: 8081   #---指定监控数据端口为8081
  endpoints:
    web:
      exposure:
        include: "*"

7.3、执行 Maven打包、Docker编译与推送

执行 Maven 打包,然后执行 Docker 镜像构建,构建完成后推送到 Docker 仓库,和上面 SpringBoot Admin 时保持一致

$ mvn clean package
$ docker build -t infvieclub/springboot-helloworld:0.0.1 .
$ docker push infvieclub/springboot-helloworld:0.0.1

7.4、配置 Kubernetes 中部署应用的 yaml 文件

注意: 且在 Kubernetes 部署的 yaml 文件中 Service 必须设置一个”admin: enabled”标签,然后配置的8081端口名称必须和 SpringBoot Admin 配置中”primaryPortName”参数设置监控端口的名称保持一致,设置为“management”,否则将无法监控到,因为SpringBoot Admin配置的监控条件是监控 Service 中带 “admin: enabled” 标签,且存在端口名称为 版权声明:本文遵循 CC 4.0 BY-SA 版权协议,若要转载请务必附上原文出处链接及本声明,谢谢合作!220;management” 的服务。

springboot-helloworld.yaml

apiVersion: v1
kind: Service
metadata:
  name: springboot-helloworld
  labels:
    app: springboot-helloworld
    admin: enabled            #---设置此标签,表示此应用被 Springboot Admin 服务发现
  annotations:
spec:
  type: ClusterIP
  ports:
    - name: server
      port: 8080             
      targetPort: 8080
    - name: management        #---指定监控端口名,表示此应用被 Springboot Admin 服务发现 
      port: 8081
      targetPort: 8081
  selector:
    app: springboot-helloworld
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: springboot-helloworld
  labels:
    app: springboot-helloworld
spec:
  replicas: 2                 #---设置副本数为2
  selector:
    matchLabels:
      app: springboot-helloworld
  template:
    metadata:
      labels:
        app: springboot-helloworld
    spec:
      containers:
      - name: springboot-helloworld
        image: infvieclub/springboot-helloworld:0.0.1
        imagePullPolicy: Always
        ports:
        - containerPort: 8080
          name: server
        - containerPort: 8081
          name: management
        resources: 
          limits:
            cpu: 1000m
            memory: 512Mi
          requests:
            cpu: 500m
            memory: 256Mi

7.5、执行 Kubectl 命令创建应用

$ kubectl apply -f springboot-helloworld.yaml -n infviecloud

7.6、SpringBoot Admin 中查看信息

在此访问 SpringBoot Admin 页面,可以看到已经监控到新增应用信息,且正确的监控到此应用有两个副本。

八、添加安全模块

经过上面测试,已经 SpringBoot Admin 能够成功监控 Kubernetes 某个 Namespace 下的服务了,不过还有一个问题,就是这个地址一打开就能进去,这样并不安全,好在 SpringBoot Admin 可以和 Spring Security 配合,组成一套简单的安全验证的登录逻辑,如下:

8.1、Maven 引入 Spring Security 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

8.2、添加配置 Security 配置类

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

@Configuration
public class LoginSecurity extends WebSecurityConfigurerAdapter {

    private String adminContextPath;

    public LoginSecurity(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");

        http.authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                .antMatchers(adminContextPath + "/actuator/health").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                .logout().logoutUrl(adminContextPath + "/logout").and()
                .httpBasic().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(
                        adminContextPath + "/instances",
                        adminContextPath + "/actuator/**"
                );
    }

}

8.3、配置文件中添加静态用户名、密码

由于是简单安全验证,所以将用户名、密码配置在配置文件中。

spring:
  security:
    user:
      name: "admin"
      password: "123456"

8.4、重新部署进行测试

还是用上面的部署 yaml 文件重新部署 SpringBoot Admin 到 Kubernetes 环境,命令如下:

$ kubectl apply -f springboot-admin-k8s.yaml -n infviecloud

部署完成后重新访问 http://192.168.2.11:30080 地址,然后可以看到如下登录界面:

0 条回应