Skip to content
清晨的一缕阳光
返回

Kubernetes 实战

Kubernetes 实战

Kubernetes(K8s)是容器编排的事实标准,提供自动部署、弹性伸缩、服务发现等能力。本文详解 K8s 核心概念,并提供 Java 应用部署的完整实践。

一、K8s 核心概念

1.1 架构组件

graph TB
    subgraph ControlPlane[控制平面]
        API[API Server]
        ETCD[(etcd)]
        SCH[Scheduler]
        CM[Controller Manager]
    end
    
    subgraph DataPlane[数据平面]
        Node1[Worker Node 1]
        Node2[Worker Node 2]
        
        subgraph Node1Components
            Kubelet1[Kubelet]
            KubeProxy1[Kube-proxy]
            Pod1[Pod 1]
            Pod2[Pod 2]
        end
        
        subgraph Node2Components
            Kubelet2[Kubelet]
            KubeProxy2[Kube-proxy]
            Pod3[Pod 3]
        end
    end
    
    API --> ETCD
    API --> SCH
    API --> CM
    API --> Kubelet1
    API --> Kubelet2
    Kubelet1 --> Pod1
    Kubelet1 --> Pod2
    Kubelet2 --> Pod3

1.2 核心资源

资源说明用途
Pod最小调度单元容器组
Deployment无状态应用应用部署
StatefulSet有状态应用数据库等
Service服务抽象负载均衡
ConfigMap配置管理配置文件
Secret敏感信息密码、密钥
Ingress入口规则HTTP 路由

二、Java 应用部署

2.1 基础 Deployment

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
  labels:
    app: order-service
    version: v1
spec:
  replicas: 3
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
        version: v1
    spec:
      containers:
        - name: order-service
          image: registry.example.com/order-service:1.0.0
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 8080
              name: http
          env:
            - name: SPRING_PROFILES_ACTIVE
              value: "prod"
            - name: JAVA_OPTS
              value: "-Xms512m -Xmx512m -XX:+UseG1GC"
          resources:
            requests:
              cpu: "500m"
              memory: "512Mi"
            limits:
              cpu: "1000m"
              memory: "1Gi"
          livenessProbe:
            httpGet:
              path: /actuator/health/liveness
              port: 8080
            initialDelaySeconds: 60
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /actuator/health/readiness
              port: 8080
            initialDelaySeconds: 30
            periodSeconds: 5

2.2 Service 配置

# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: order-service
spec:
  selector:
    app: order-service
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP  # 集群内部访问

Service 类型对比

mindmap
  root((Service 类型))
    ClusterIP
      集群内部访问
      默认类型
    NodePort
      节点端口暴露
      30000-32767
    LoadBalancer
      云厂商负载均衡
      自动分配 IP
    ExternalName
      DNS CNAME
      外部服务

2.3 ConfigMap 管理配置

# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: order-service-config
data:
  application.yml: |
    server:
      port: 8080
    spring:
      datasource:
        url: jdbc:mysql://mysql:3306/order_db
        driver-class-name: com.mysql.cj.jdbc.Driver
      redis:
        host: redis
        port: 6379
    logging:
      level:
        com.example: INFO

使用 ConfigMap

apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
spec:
  template:
    spec:
      containers:
        - name: order-service
          image: order-service:1.0.0
          envFrom:
            - configMapRef:
                name: order-service-config
          volumeMounts:
            - name: config
              mountPath: /app/config
      volumes:
        - name: config
          configMap:
            name: order-service-config

2.4 Secret 管理敏感信息

# secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: order-service-secret
type: Opaque
stringData:
  DB_USERNAME: appuser
  DB_PASSWORD: app123
  JWT_SECRET: your-secret-key-here

创建 Secret 的三种方式

# 方式 1:命令行创建
kubectl create secret generic order-secret \
  --from-literal=DB_USERNAME=appuser \
  --from-literal=DB_PASSWORD=app123

# 方式 2:从文件创建
kubectl create secret generic order-secret \
  --from-file=application-prod.yml

# 方式 3:Base64 编码
echo -n 'app123' | base64
# 输出:YXBwMTIz

三、高级特性

3.1 自动扩缩容(HPA)

# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: order-service-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: order-service
  minReplicas: 3
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80

HPA 工作流程

graph LR
    Metrics[Metrics Server] -->|CPU/内存 | HPA[HPA Controller]
    HPA -->|调整副本数 | Deploy[Deployment]
    Deploy -->|创建/删除 | Pod[Pod]

3.2 滚动更新

# 查看更新状态
kubectl rollout status deployment/order-service

# 更新镜像
kubectl set image deployment/order-service \
  order-service=order-service:1.1.0

# 查看更新历史
kubectl rollout history deployment/order-service

# 回滚到上一个版本
kubectl rollout undo deployment/order-service

# 回滚到指定版本
kubectl rollout undo deployment/order-service --to-revision=2

滚动更新策略

spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1        # 最多超出副本数的 Pod 数
      maxUnavailable: 0  # 最多不可用的 Pod 数

3.3 健康检查

livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    port: 8080
  initialDelaySeconds: 60   # 容器启动后 60 秒开始检查
  periodSeconds: 10         # 每 10 秒检查一次
  timeoutSeconds: 3         # 超时时间 3 秒
  failureThreshold: 3       # 失败 3 次重启容器

readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 5
  timeoutSeconds: 3
  failureThreshold: 3       # 失败 3 次从 Service 移除

探针类型对比

探针失败动作用途
livenessProbe重启容器检测死锁
readinessProbe从 Service 移除检测就绪状态
startupProbe重启容器检测慢启动应用

四、实战案例

4.1 完整部署配置

# complete-deployment.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: order-service-config
  namespace: production
data:
  SPRING_PROFILES_ACTIVE: "prod"
  LOGGING_LEVEL_COM_EXAMPLE: "INFO"
---
apiVersion: v1
kind: Secret
metadata:
  name: order-service-secret
  namespace: production
type: Opaque
stringData:
  DB_USERNAME: appuser
  DB_PASSWORD: ${DB_PASSWORD}
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
  namespace: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
    spec:
      containers:
        - name: order-service
          image: registry.example.com/order-service:1.0.0
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: order-service-config
            - secretRef:
                name: order-service-secret
          resources:
            requests:
              cpu: "500m"
              memory: "512Mi"
            limits:
              cpu: "1000m"
              memory: "1Gi"
          livenessProbe:
            httpGet:
              path: /actuator/health/liveness
              port: 8080
            initialDelaySeconds: 60
          readinessProbe:
            httpGet:
              path: /actuator/health/readiness
              port: 8080
            initialDelaySeconds: 30
---
apiVersion: v1
kind: Service
metadata:
  name: order-service
  namespace: production
spec:
  selector:
    app: order-service
  ports:
    - port: 80
      targetPort: 8080
  type: ClusterIP
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: order-service-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: order-service
  minReplicas: 3
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

4.2 部署命令

# 创建命名空间
kubectl apply -f complete-deployment.yaml

# 查看所有资源
kubectl get all -n production

# 查看 Pod 状态
kubectl get pods -n production -l app=order-service

# 查看日志
kubectl logs -f deployment/order-service -n production

# 进入容器
kubectl exec -it deployment/order-service -n production -- /bin/sh

# 端口转发(本地访问)
kubectl port-forward deployment/order-service 8080:8080 -n production

4.3 监控配置

# PodMonitor 配置(Prometheus Operator)
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: order-service
  namespace: production
spec:
  selector:
    matchLabels:
      app: order-service
  podMetricsEndpoints:
    - port: http
      path: /actuator/prometheus
      interval: 30s

五、最佳实践

5.1 资源管理

resources:
  requests:
    cpu: "500m"      # 保证资源
    memory: "512Mi"
  limits:
    cpu: "1000m"     # 最大资源
    memory: "1Gi"

资源管理建议

mindmap
  root((资源管理))
    requests
      保证资源
      调度依据
      不能超卖
    limits
      最大限制
      防止资源耗尽
      可能被 OOM Kill

5.2 标签规范

metadata:
  labels:
    app: order-service        # 应用名称
    version: v1               # 版本号
    component: backend        # 组件类型
    environment: production   # 环境
    team: order-team          # 团队

5.3 安全实践

spec:
  securityContext:
    runAsNonRoot: true        # 非 root 用户
    runAsUser: 1000           # 用户 ID
    fsGroup: 1000             # 组 ID
  
  containers:
    - securityContext:
        allowPrivilegeEscalation: false  # 禁止提权
        readOnlyRootFilesystem: true     # 只读文件系统
        capabilities:
          drop:
            - ALL                        # 删除所有能力

六、总结

6.1 核心要点

  1. Pod:K8s 最小调度单元
  2. Deployment:无状态应用部署
  3. Service:服务抽象和负载均衡
  4. ConfigMap/Secret:配置和敏感信息管理
  5. HPA:自动扩缩容
  6. 健康检查:liveness/readiness 探针

6.2 学习路线

graph LR
    A[基础概念<br/>Pod/Deployment/Service] --> B[配置管理<br/>ConfigMap/Secret]
    B --> C[服务发现<br/>Ingress/ServiceMesh]
    C --> D[监控告警<br/>Prometheus/Grafana]
    D --> E[自动运维<br/>HPA/Operator]

Kubernetes 是云原生的操作系统,掌握 K8s 是 Java 开发者的必备技能


参考资料


分享这篇文章到:

下一篇文章
事件驱动架构设计