以下是 Kubernetes 服务编排 的全面指南,涵盖核心资源、实战场景、云平台适配及高级模式,帮助你构建弹性、高可用的分布式应用!
Kubernetes 服务编排 的全面指南
一、Kubernetes 核心服务编排资源
1. 基础资源
资源类型 | 作用 | 示例配置 |
---|---|---|
Deployment | 定义应用副本数、镜像、更新策略 | spec.replicas: 3 |
Service | 提供稳定访问入口(负载均衡、服务发现) | spec.type: LoadBalancer |
Ingress | 管理外部流量路由(路径、主机、SSL 终止) | spec.rules.http.paths.path: /api |
PersistentVolumeClaim (PVC) | 存储卷声明(如 MySQL 数据库) | spec.resources.requests.storage: 10Gi |
ConfigMap | 管理环境变量、配置文件 | data: {"app.env": "production"} |
Secret | 存储敏感信息(如数据库密码) | type: OpaqueData |
2. 高级编排模式
滚动更新(Rolling Update)
# Deployment 配置示例
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # 最多同时更新 1 个 Pod
maxUnavailable: 0 # 不可用水 Pod 数为 0
蓝绿部署(Blue-Green Deploy)
# 使用 Service 切换流量
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: blue-green-ingress
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: green-service
weight: 100
- path: /
pathType: Prefix
backend:
service:
name: blue-service
weight: 0
二、云平台适配:AKS/GKE/EKS
1. AWS EKS 集群部署
# 创建集群(自动配置 VPC、IAM)
eksctl create cluster \
--name my-eks-cluster \
--region us-west-2 \
--nodes 3
2. GKE 集群部署
gcloud config set project my-gcp-project
gcloud container clusters create my-gke-cluster \
--zone us-central1-a \
--num-nodes 3
3. Azure AKS 集群部署
az group create --name my-rg --location eastus
az aks create \
--resource-group my-rg \
--name my-aks-cluster \
--node-count 3 \
--enable-addons monitoring,logging
三、实战场景:微服务架构编排
1. 多容器应用部署
示例:Nginx + MySQL + Redis
# nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 2
template:
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
# mysql-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: mysql
spec:
replicas: 1
template:
spec:
containers:
- name: mysql
image: mysql:5.7
env:
- name: MYSQL_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mysql-password
key: password
2. 服务发现与负载均衡
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: my-app
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer
3. 持久化存储(MySQL 数据库)
# pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
# mysql-deployment.yaml(更新)
spec:
volumes:
- name: mysql-storage
persistentVolumeClaim:
claimName: mysql-pvc
volumeMounts:
- name: mysql-storage
mountPath: /var/lib/mysql
四、高级编排技巧
1. 自动扩缩容
# HorizontalPodAutoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
2. 服务网格(Istio)集成
# Istio VirtualService
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: my-app
spec:
hosts:
- my-app.default.svc.cluster.local
http:
- match:
- uri:
prefix: /api
route:
- to:
host: my-app.default.svc.cluster.local
weight: 100
- to:
host: fallback-service.default.svc.cluster.local
weight: 0
3. CI/CD 流水线(Argo CD)
# Application Manifest
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: my-app
spec:
project: default
source:
repoURL: https://github.com/your-org/my-app
targetRevision: HEAD
deployment:
strategy:
blueGreen:
prePromotionAnalysis:
template:
spec:
containers:
- name: analysis
image: argoproj/analysis-tool:latest
五、监控与日志
1. Prometheus + Grafana
# Prometheus Rule
- alert: HighCPUUsage
expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.1
for: 10m
labels:
team: backend
2. ELK 日志收集
# Fluentd ConfigMap
apiVersion: logging.fluentd.org/v1alpha1
kind: FluentdConfig
metadata:
name: my-fluentd
spec:
configMap:
data:
fluent.conf: |
<source>
@type tail
path /var/log/containers/*.log
pos_file /var/log/fluentd-containers.pos
</source>
<match >
@type elasticsearch
host elasticsearch-host
port 9200
</match>
六、安全与权限
1. RBAC 配置
# RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: dev-team
spec:
roleRef:
kind: ClusterRole
name: developer
subjects:
- kind: User
name: dev-user
email: dev-user@example.com
2. 网络策略
# NetworkPolicy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-ssh
spec:
podSelector:
matchLabels:
app: my-app
ingress:
- from:
- ipBlock:
cidr: 10.0.0.0/8
ports:
- protocol: TCP
port: 22
七、常见问题与解决方案
1. 服务无法访问
• 检查步骤:
kubectl get endpoints
确认 Service 是否分配了 IP。kubectl describe service
查看负载均衡器状态。- 云平台防火墙规则是否允许流量(如 AWS ALB 安全组)。
2. 部署滚动更新失败
• 常见原因:
• 镜像拉取失败(检查 imagePullSecrets
)。
• 资源限制(CPU/内存不足,调整 resources.requests
)。
3. 数据库持久化丢失
• 解决方案:
• 确保 PersistentVolume
已正确挂载。
• 使用 StatefulSet
替代 Deployment
(适用于有状态服务)。
八、工具链推荐
- GitOps:Argo CD(声明式部署)、Flux(自动同步 Git 仓库)。
- 监控:Prometheus + Grafana、Datadog、Loki。
- 日志:ELK Stack(Elasticsearch, Logstash, Kibana)、Fluentd。
- CI/CD:Jenkins Pipeline、GitLab CI、Tekton。
九、实战案例:电商平台后端
1. 系统架构
2. 核心服务
服务名称 | 职责 | 镜像 |
---|---|---|
user-service | 用户注册、登录 | nginx:latest |
order-service | 订单处理 | spring-boot:2.7.18 |
payment-service | 支付集成(Stripe) | nodejs:16-alpine |
redis-cache | 缓存热点数据 | redis:alpine |
3. 关键配置
# Ingress 配置(多路径路由)
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: e-commerce-ingress
spec:
rules:
- host: shop.example.com
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: user-service
port:
number: 8080
- path: /orders
pathType: Prefix
backend:
service:
name: order-service
port:
number: 8080
通过以上指南,你可以掌握 Kubernetes 服务编排的核心技能,构建从开发到生产的完整云原生应用!如果有具体需求(如混沌工程测试),欢迎进一步讨论。 🚀