spring+k8s 功能说明

发布于:2025-03-25 ⋅ 阅读:(40) ⋅ 点赞:(0)

以下是一个结合 Kubernetes(k8s)Spring Boot 的完整实例,涵盖应用开发、容器化、部署到 Kubernetes 集群的全流程。


1. 创建 Spring Boot 应用

1.1 项目初始化

使用 Spring Initializr 生成一个简单的 REST API 项目:
依赖项:Spring Web、Actuator(用于健康检查)
示例代码

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello from Spring Boot on Kubernetes!";
    }
}
1.2 添加健康检查(Actuator)

确保 application.properties 启用 Actuator 端点:

management.endpoints.web.exposure.include=health,info
management.endpoint.health.probes.enabled=true

2. 容器化应用(Docker)

2.1 编写 Dockerfile

在项目根目录创建 Dockerfile

# 使用多阶段构建减小镜像体积
FROM maven:3.8.6-jdk-11 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src/ ./src/
RUN mvn package -DskipTests

# 运行时镜像
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
2.2 构建镜像
docker build -t spring-boot-k8s-demo:1.0.0 .

3. 编写 Kubernetes 配置文件

3.1 Deployment

创建 deployment.yaml,定义如何运行 Spring Boot 应用:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: spring-boot-demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: spring-boot-demo
  template:
    metadata:
      labels:
        app: spring-boot-demo
    spec:
      containers:
      - name: app
        image: spring-boot-k8s-demo:1.0.0
        ports:
        - containerPort: 8080
        livenessProbe:          # 存活探针
          httpGet:
            path: /actuator/health/liveness
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:         # 就绪探针
          httpGet:
            path: /actuator/health/readiness
            port: 8080
          initialDelaySeconds: 20
          periodSeconds: 5
3.2 Service

创建 service.yaml,暴露应用服务(ClusterIP 类型):

apiVersion: v1
kind: Service
metadata:
  name: spring-boot-demo-service
spec:
  selector:
    app: spring-boot-demo
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
3.3 Ingress(可选)

创建 ingress.yaml,配置外部访问(需安装 Ingress 控制器):

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: spring-boot-ingress
spec:
  rules:
  - host: spring-boot.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: spring-boot-demo-service
            port:
              number: 80

4. 部署到 Kubernetes 集群

4.1 推送镜像到仓库(可选)

若使用私有仓库(如 Docker Hub、Harbor):

docker tag spring-boot-k8s-demo:1.0.0 <your-registry>/spring-boot-k8s-demo:1.0.0
docker push <your-registry>/spring-boot-k8s-demo:1.0.0

修改 deployment.yaml 中的镜像地址。

4.2 部署应用
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f ingress.yaml  # 如果需要外部访问
4.3 验证部署
# 查看 Pod 状态
kubectl get pods -l app=spring-boot-demo

# 查看 Service
kubectl get svc spring-boot-demo-service

# 访问应用(通过 Ingress 或 Port-Forward)
kubectl port-forward svc/spring-boot-demo-service 8080:80
curl http://localhost:8080/hello

5. 高级配置

5.1 使用 ConfigMap 管理配置

创建 configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  application.properties: |
    server.port=8080
    greeting.message=Hello from ConfigMap!

修改 Deployment,挂载 ConfigMap:

spec:
  containers:
  - name: app
    # ...
    volumeMounts:
    - name: config-volume
      mountPath: /app/config
  volumes:
  - name: config-volume
    configMap:
      name: app-config
5.2 自动扩缩容(HPA)

创建 hpa.yaml

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: spring-boot-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: spring-boot-demo
  minReplicas: 2
  maxReplicas: 5
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50

6. 监控与日志

6.1 集成 Prometheus

pom.xml 添加 Micrometer 依赖:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

修改 application.properties 暴露 Prometheus 端点:

management.endpoints.web.exposure.include=health,info,prometheus
6.2 配置 ServiceMonitor(需 Prometheus Operator)

创建 service-monitor.yaml

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: spring-boot-monitor
spec:
  selector:
    matchLabels:
      app: spring-boot-demo
  endpoints:
  - port: http
    path: /actuator/prometheus

总结

通过以上步骤,你可以将 Spring Boot 应用部署到 Kubernetes 集群,并实现以下功能:
容器化:通过 Docker 打包应用。
健康检查:利用 Actuator 端点实现存活和就绪探针。
服务发现:通过 Service 和 Ingress 暴露应用。
配置管理:使用 ConfigMap 分离环境配置。
自动扩缩容:通过 HPA 动态调整副本数。
监控:集成 Prometheus 监控应用指标。