微服务 Kubernetes 部署
容器化之后,Kubernetes(K8s)接管编排:自动调度、故障自愈、滚动更新、弹性扩缩。本文从微服务视角讲透 Pod、Service、ConfigMap、Secret、Deployment、HPA 等核心资源,以及资源限制与 QoS 的配置方法。
K8s 核心概念
微服务与 K8s 的映射
微服务架构在 K8s 中的落地:
├─ 每个微服务 = 一个 Deployment(管理 Pod 副本)
├─ 服务间调用 = Service(稳定的虚拟 IP + DNS)
├─ 外部入口 = Ingress(HTTP 路由)
├─ 配置 = ConfigMap + Secret
└─ 弹性伸缩 = HPA(水平自动扩缩)控制面与工作节点
K8s 集群组成:
├─ 控制面(Master):
│ ├─ API Server:所有操作的入口
│ ├─ Scheduler:决定 Pod 调度到哪个节点
│ ├─ Controller Manager:维持期望状态
│ └─ etcd:集群状态存储
└─ 工作节点(Worker):
├─ kubelet:管理本节点 Pod
├─ kube-proxy:实现 Service 转发
└─ 容器运行时(containerd)一、Pod 与探针
Pod 是什么
Pod = K8s 最小调度单元:
├─ 一个 Pod 可以包含多个容器(通常 1 个业务容器 + Sidecar)
├─ 同一 Pod 共享网络与存储
└─ 微服务实践中:1 个 Pod 1 个业务容器(+ 可选 Sidecar)探针配置
yaml
apiVersion: v1
kind: Pod
metadata:
name: order-service-pod
spec:
containers:
- name: order-service
image: registry.example.com/order-service:1.0.0
ports:
- containerPort: 8080
startupProbe: # 启动探针:给 JVM 启动时间
httpGet:
path: /actuator/health
port: 8080
failureThreshold: 30
periodSeconds: 5
livenessProbe: # 存活探针:卡死则重启
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 60
periodSeconds: 15
readinessProbe: # 就绪探针:就绪才接流量
httpGet:
path: /actuator/health/readiness
port: 8080
periodSeconds: 10探针的职责
| 探针 | 失败处理 | 作用 |
|---|---|---|
| livenessProbe | 重启容器 | 检测进程/应用卡死 |
| readinessProbe | 摘除 Service 端点 | 检测是否就绪接流量 |
| startupProbe | 延迟其他探针 | 慢启动应用保护 |
二、Deployment 部署
Deployment 清单
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
labels:
app: order-service
spec:
replicas: 3 # 副本数
selector:
matchLabels:
app: order-service
strategy:
type: RollingUpdate # 滚动更新
rollingUpdate:
maxSurge: 1 # 更新时最多多出 1 个副本
maxUnavailable: 0 # 更新时不可用副本数 ≤ 0(先起新后停旧)
template:
metadata:
labels:
app: order-service
spec:
containers:
- name: order-service
image: registry.example.com/order-service:1.0.0
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: prod
- name: NACOS_ADDR
value: nacos.default.svc.cluster.local:8848
resources:
requests: # 请求量(调度依据)
cpu: 500m
memory: 512Mi
limits: # 上限(限制使用)
cpu: "1"
memory: 1Gi
imagePullPolicy: IfNotPresent滚动更新策略
滚动更新(RollingUpdate):
├─ maxSurge:更新期间允许超出副本数的额外 Pod 数
├─ maxUnavailable:允许不可用的最大 Pod 数
├─ 例:maxSurge=1, maxUnavailable=0
│ 先启动 1 个新版本 Pod → 就绪后停 1 个旧 Pod → 循环
└─ 效果:更新过程不中断服务
回滚:
kubectl rollout undo deployment/order-service
└─ K8s 保留历史版本,一键回滚Deployment 状态管理
Deployment 自愈:
├─ Pod 崩溃 → ReplicaSet 自动重建
├─ 节点宕机 → Pod 被调度到其他节点
└─ 期望状态与当前状态由 Controller 持续调谐三、Service 服务暴露
Service 的作用
Service 解决 Pod 动态变化的问题:
├─ Pod IP 会随重建变化 → 不能直接用
├─ Service 提供稳定虚拟 IP + DNS 名称
└─ 微服务间通过 Service 名调用(order-service → 集群内 DNS)Service 清单
yaml
apiVersion: v1
kind: Service
metadata:
name: order-service
spec:
selector: # 关联的 Pod(按标签)
app: order-service
ports:
- port: 8080 # Service 端口
targetPort: 8080 # Pod 容器端口
type: ClusterIP # 集群内访问Service 类型
| 类型 | 访问范围 | 适用场景 |
|---|---|---|
| ClusterIP | 集群内 | 微服务间调用(默认) |
| NodePort | 节点 IP + 端口 | 测试环境外部访问 |
| LoadBalancer | 云负载均衡 | 对外服务(配合云厂商) |
| ExternalName | 集群外域名 | 代理外部服务 |
微服务间的调用
Spring Cloud 服务在 K8s 中的寻址:
├─ 方式一:仍用 Nacos 注册发现(Pod 注册到 Nacos)
│ ├─ Pod 重建后重新注册,Nacos 摘除旧实例
│ └─ 网关经 Nacos 路由到服务
├─ 方式二:直接用 K8s Service 名 + 端口
│ ├─ 每个 Deployment 对应一个 Service
│ └─ OpenFeign URL 配 http://order-service:8080
└─ 混合:网关走 Nacos,内部走 Service(常见)
K8s 内 DNS:
服务名.namespace.svc.cluster.local
├─ order-service.default.svc.cluster.local
└─ 同 namespace 可简写 order-service四、ConfigMap 与 Secret
ConfigMap 配置管理
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: order-service-config
data:
application.yml: | # 挂载整个配置文件
server:
port: 8080
spring:
cloud:
nacos:
server-addr: nacos.default.svc.cluster.local:8848
business:
max-order-count: 100yaml
# Deployment 中引用 ConfigMap
spec:
containers:
- name: order-service
envFrom:
- configMapRef:
name: order-service-config
volumeMounts:
- name: config
mountPath: /app/config
volumes:
- name: config
configMap:
name: order-service-configSecret 敏感信息
yaml
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
stringData:
DB_USERNAME: order_app
DB_PASSWORD: s3cr3t-passyaml
# Deployment 引用 Secret
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: db-credentials
key: DB_USERNAME
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: DB_PASSWORD配置管理最佳实践
├─ 环境差异用多个 ConfigMap(dev/test/prod)
├─ 敏感信息必须走 Secret(不能明文写 ConfigMap)
├─ Secret 生产建议接外部密钥管理(Vault / 云厂商 KMS)
├─ 配置变更后重启滚动(config 变化不自动触发滚动)
└─ Spring 侧可用 ConfigMap + 配置中心双重管理五、资源限制与 QoS
requests 与 limits
资源模型:
├─ requests:调度依据(保证可得资源)
├─ limits:使用上限(超出被限制/杀掉)
├─ cpu 单位:m(1000m = 1 核)
└─ memory 单位:Mi / Gi
Java 应用关键:
├─ limits.memory 要与 JVM -Xmx 对齐
├─ 否则容器超限被 OOMKilled,JVM 却还没触发 GC 调优
└─ 建议:-Xmx ≈ limits.memory × 60%-75%(留余量给堆外)QoS 等级
K8s 按 requests/limits 划分 QoS 等级(内存不足时的杀 Pod 顺序):
├─ Guaranteed:requests == limits(最高优先,最后被杀)
├─ Burstable:requests < limits(中等)
└─ BestEffort:无 requests/limits(最低优先,最先被杀)
微服务建议:
├─ 核心服务用 Guaranteed(requests == limits)
└─ 非核心可 BurstableHPA 自动扩缩
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: 60 # CPU 使用率超 60% 扩容
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70HPA 工作原理:
├─ 周期采集 Pod 指标(Metrics Server)
├─ 按平均使用率计算目标副本数
├─ 目标副本数 = ceil(当前副本数 × 当前使用率/目标使用率)
├─ 扩容快(默认 15s 评估一次)
└─ 缩容慢(默认 5 分钟冷却,防抖动)
与微服务结合:
├─ 业务量有周期性 → HPA 自动扩缩
├─ 配合 Nacos 实例摘除/注册(优雅上下线)
└─ 大促可临时调整 minReplicas 预热六、Ingress 网关入口
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: gateway-ingress
spec:
rules:
- host: api.example.com
http:
paths:
- path: /order
pathType: Prefix
backend:
service:
name: gateway
port:
number: 8080Ingress 的作用:
├─ 集群统一入口(7 层 HTTP 路由)
├─ 按 host/path 转发到不同 Service
├─ 支持 TLS、限流、重写(依赖 Ingress Controller)
└─ 微服务网关(Gateway)挂在 Ingress 后面七、微服务部署完整示例
一个微服务在 K8s 的完整资源:
├─ ConfigMap:配置文件
├─ Secret:数据库密码
├─ Deployment:应用实例(含探针、资源)
├─ Service:集群内访问
├─ HPA:自动扩缩
└─ Ingress:对外暴露(经网关)
部署命令:
kubectl apply -f order-service-deployment.yaml
kubectl apply -f order-service-service.yaml
kubectl apply -f order-service-hpa.yaml生产部署清单
K8s 部署微服务检查清单:
├─ 1. 探针三件套(startup/liveness/readiness)
├─ 2. 资源 requests/limits 明确,JVM 内存对齐
├─ 3. Secret 管理敏感信息,杜绝明文
├─ 4. 滚动更新策略合理(maxSurge/maxUnavailable)
├─ 5. HPA 配置 CPU/内存自动扩缩
├─ 6. 日志采集(stdout + 采集器)
├─ 7. Pod 优雅终止(preStop + 宽限期)
└─ 8. 镜像标签可追溯,支持回滚总结
K8s 把微服务的部署抽象成声明式资源:Deployment 声明副本与更新策略,Service 提供稳定寻址,ConfigMap/Secret 分离配置与密钥,HPA 按指标自动扩缩。落地微服务到 K8s 的关键是探针保可用、资源限制防失控、Secret 保安全、HPA 保弹性,配合 Nacos 等服务治理组件,就能构建一套自愈、可扩缩的微服务运行平台。