← 返回首页 📚 实战课程
📑 本篇章节导航 (共5章,点击直达)
本节目标(学完能回答的面试题)核心知识(1小时精讲内容)面试速记卡(考前30秒速看)练习题(自测)学习资料

L38 - K8S进阶

本节目标(学完能回答的面试题)

核心知识(1小时精讲内容)

1. 核心资源层级


K8S资源层级(从大到小):

Cluster (集群)
└── Namespace (命名空间,资源隔离)
    └── Deployment (无状态工作负载)
        └── ReplicaSet (副本集,管理Pod副本数)
            └── Pod (最小调度单元)
                └── Container (容器)
                    
  还有:
  StatefulSet (有状态服务,如MySQL主从)
  DaemonSet (每个节点运行一个Pod,如日志采集)
  Job / CronJob (一次性/定时任务)

# Deployment管理Nginx示例
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
  namespace: production
spec:
  replicas: 3                    # Pod副本数
  selector:
    matchLabels:
      app: order-service
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1               # 滚动更新时,最多多出1个Pod
      maxUnavailable: 0         # 滚动更新时,不允许有Pod不可用
  template:                     # Pod模板
    metadata:
      labels:
        app: order-service
    spec:
      containers:
        - name: order-service
          image: harbor.company.com/app/order-service:v1.2.0
          ports:
            - containerPort: 8080
          resources:
            requests:            # 调度依据(最少保证)
              memory: "256Mi"
              cpu: "200m"        # 200m = 0.2核
            limits:              # 硬限制(最多使用)
              memory: "512Mi"
              cpu: "500m"

2. Service与Ingress

Service三种类型:


类型           访问方式                  适用场景
──────────────────────────────────────────────────
ClusterIP     集群内部虚拟IP              微服务间调用
              (默认类型)

NodePort      节点IP:30000-32767         测试环境/简单暴露
              (每个节点都监听)

LoadBalancer  云厂商LB → NodePort         生产环境外部访问
              (需要云支持)

                    Ingress (七层路由)
                       │
           ┌───────────┼───────────┐
           ▼           ▼           ▼
     /api/order   /api/user   /api/pay
           │           │           │
           ▼           ▼           ▼
    order-svc     user-svc    pay-svc
   (ClusterIP)   (ClusterIP) (ClusterIP)
           │           │           │
           ▼           ▼           ▼
     Pod●●●      Pod●●●      Pod●●●

# Ingress路由配置
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  ingressClassName: nginx
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /api/order(/|$)(.*)
            pathType: Prefix
            backend:
              service:
                name: order-service
                port:
                  number: 8080
          - path: /api/user(/|$)(.*)
            pathType: Prefix
            backend:
              service:
                name: user-service
                port:
                  number: 8080

3. HPA自动伸缩


# HPA配置 — 基于CPU和自定义指标
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: order-service-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: order-service
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70      # CPU使用率 > 70% 扩容
    - type: Pods
      pods:
        metric:
          name: http_requests_per_second
        target:
          type: AverageValue
          averageValue: "1000"         # QPS > 1000 扩容
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 60  # 扩容冷却期60秒
      policies:
        - type: Percent
          value: 100                   # 最多一次翻倍
          periodSeconds: 60
    scaleDown:
      stabilizationWindowSeconds: 300  # 缩容冷却期5分钟
      policies:
        - type: Percent
          value: 25                    # 一次最多缩25%
          periodSeconds: 60

HPA工作原理:


Metrics Server → 收集Pod指标
        │
        ▼
HPA Controller → 每15秒计算一次
        │
        ├── 当前指标 > 目标值 → 增加副本
        │   desired = current × (currentMetric / targetMetric)
        │
        ├── 当前指标 < 目标值 → 减少副本(冷却期后)
        │
        └── 修改Deployment.replicas
                │
                ▼
           ReplicaSet创建/删除Pod

4. ConfigMap与Secret


# ConfigMap — 非敏感配置
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  SPRING_PROFILES_ACTIVE: "prod"
  LOG_LEVEL: "INFO"
  application.yml: |
    server:
      port: 8080
    spring:
      redis:
        host: redis-service

---
# Secret — 敏感配置(Base64编码,不是加密!)
apiVersion: v1
kind: Secret
metadata:
  name: db-secret
type: Opaque
data:
  DB_PASSWORD: cGFzc3dvcmQxMjM=   # echo -n 'password123' | base64
stringData:                          # 明文写入,自动编码
  DB_USERNAME: "root"

5. 探针三件套


三种探针的生命周期顺序:

  Pod启动
    │
    ▼
  Startup Probe (启动探针)
  - 确认应用已启动
  - 失败→重启容器
  - 成功→进入就绪检测
    │
    ▼ (Startup成功后)
  Readiness Probe (就绪探针)
  - 确认应用可接收流量
  - 失败→从Service摘除(不路由)
  - 成功→加入Service端点
    │
    ▼ (持续检测)
  Liveness Probe (存活探针)
  - 确认应用运行正常
  - 失败→重启容器(杀伤力最大)
  - 成功→继续运行

# 探针配置示例
startupProbe:
  httpGet:
    path: /actuator/health/liveness
    port: 8080
  failureThreshold: 30     # 允许失败30次
  periodSeconds: 10        # 每10秒检测
  # 最多等待 30×10=300秒 启动

readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    port: 8080
  initialDelaySeconds: 30  # 启动后30秒开始检测
  periodSeconds: 10
  failureThreshold: 3

livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    port: 8080
  initialDelaySeconds: 60  # 启动后60秒才开始
  periodSeconds: 30
  failureThreshold: 3

6. 滚动更新策略


RollingUpdate策略:
  maxSurge: 1        # 最多多创建1个Pod
  maxUnavailable: 0  # 不允许中断

更新过程(replicas=3):
  1. 创建新Pod(Pod4)        → [Pod1, Pod2, Pod3, Pod4]
  2. Pod4就绪后删除Pod1      → [Pod2, Pod3, Pod4]
  3. 创建新Pod(Pod5)        → [Pod2, Pod3, Pod4, Pod5]
  4. Pod5就绪后删除Pod2      → [Pod3, Pod4, Pod5]
  5. 创建新Pod(Pod6)        → [Pod3, Pod4, Pod5, Pod6]
  6. Pod6就绪后删除Pod3      → [Pod4, Pod5, Pod6]
  
  ✅ 全程至少3个Pod可用,零停机

回滚操作:


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

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

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

7. 故障排查五步法


Step 1: 查看Pod状态
  kubectl get pods -n production
  kubectl describe pod <pod-name> -n production
  # 关注 Events 部分

Step 2: 查看Pod日志
  kubectl logs <pod-name> -n production
  kubectl logs <pod-name> --previous  # 查看上次崩溃的日志

Step 3: 进入容器排查
  kubectl exec -it <pod-name> -- /bin/sh

Step 4: 检查Service和Endpoint
  kubectl get svc -n production
  kubectl get endpoints <service-name> -n production
  # Endpoints为空→Pod不健康或Label不匹配

Step 5: 检查节点和事件
  kubectl get nodes
  kubectl describe node <node-name>
  kubectl get events -n production --sort-by='.lastTimestamp'

常见Pod状态:


状态              含义                   排查方向
──────────────────────────────────────────────────────────
Pending          调度失败                资源不足/节点选择器不匹配
CrashLoopBackOff 容器启动后崩溃          logs --previous查崩溃原因
ImagePullBackOff 镜像拉取失败            镜像地址/认证/网络问题
OOMKilled        内存超限                增大limits或优化内存
Terminating      卡在终止中              preStop钩子卡住/PV回收慢

8. 与工作实战对照


你的工作场景:
  Harbor私有镜像仓库 → imagePullSecrets配置
  ARM64架构节点     → nodeSelector: kubernetes.io/arch=arm64
  K8S CI/CD        → Jenkins Pipeline + kubectl apply
  
  实战中的YAML通常包含:
  - harbor.company.com/... 镜像地址
  - imagePullSecrets: harbor-secret
  - nodeAffinity: ARM64节点偏好
  - topologySpreadConstraints: 拓扑分布约束

面试速记卡(考前30秒速看)

练习题(自测)

1. Deployment、StatefulSet、DaemonSet分别适用于什么场景?

2. HPA的stabilizationWindowSeconds对扩容和缩容分别有什么影响?

3. Readiness探针失败和Liveness探针失败,K8S分别做什么操作?

4. Pod处于CrashLoopBackOff状态,如何排查?

5. 如何实现零停机滚动更新?maxUnavailable=0如何保证?

学习资料