最佳实践
学习目标
- 掌握 Kubernetes 生产环境最佳实践
- 理解安全、资源管理、部署策略
- 学会构建可靠的 Kubernetes 平台
核心概念
最佳实践分类
┌─────────────────────────────────────────────────────────┐
│ Kubernetes 最佳实践 │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 安全 │ │ 资源 │ │ 部署 │ │
│ │ Security │ │ Resources │ │ Deployment │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 网络 │ │ 存储 │ │ 监控 │ │
│ │ Network │ │ Storage │ │ Monitoring │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 命名空间 │ │ 配置管理 │ │ CI/CD │ │
│ │ Namespace │ │ Config │ │ Pipeline │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────┘
实践练习
练习 1:安全最佳实践
# 1. 使用非 root 用户运行
apiVersion: v1
kind: Pod
metadata:
name: security-context
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
containers:
- name: app
image: my-app:latest
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
# 2. 限制资源请求和限制
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
# 3. 使用 Network Policy
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
spec:
podSelector: {}
policyTypes:
- Ingress
# 4. 使用 Pod Security Standards
---
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
练习 2:资源管理最佳实践
# 1. 设置 Resource Quota
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
namespace: production
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
pods: "50"
# 2. 设置 Limit Range
---
apiVersion: v1
kind: LimitRange
metadata:
name: default-limits
namespace: production
spec:
limits:
- default:
cpu: "500m"
memory: "512Mi"
defaultRequest:
cpu: "100m"
memory: "128Mi"
type: Container
# 3. 使用 HPA 自动扩缩容
---
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
behavior:
scaleDown:
stabilizationWindowSeconds: 300
练习 3:部署最佳实践
# 1. 使用 Rolling Update
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
template:
spec:
containers:
- name: app
image: my-app:v1.2.3 # 使用具体版本标签,不要用 latest
readinessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
# 2. 使用 Pod Disruption Budget
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: my-app-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: my-app
# 3. 配置优雅终止
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 15"]
terminationGracePeriodSeconds: 30
练习 4:配置管理最佳实践
# 1. 使用 ConfigMap 管理配置
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
APP_ENV: "production"
LOG_LEVEL: "info"
DB_HOST: "postgres.default.svc.cluster.local"
# 2. 使用 Secret 管理敏感信息
---
apiVersion: v1
kind: Secret
metadata:
name: app-secret
type: Opaque
data:
DB_PASSWORD: cGFzc3dvcmQxMjM= # base64 编码
# 3. 使用环境变量引用
---
apiVersion: v1
kind: Pod
spec:
containers:
- name: app
envFrom:
- configMapRef:
name: app-config
- secretRef:
name: app-secret
练习 5:监控最佳实践
# 1. 暴露 Prometheus 指标
apiVersion: v1
kind: Pod
metadata:
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
spec:
containers:
- name: app
ports:
- name: metrics
containerPort: 8080
# 2. 配置告警规则
---
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: app-alerts
spec:
groups:
- name: app
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_requests_total{code=~"5.."}[5m]))
/
sum(rate(http_requests_total[5m]))
> 0.05
for: 5m
labels:
severity: critical
练习 6:命名空间最佳实践
# 1. 使用命名空间隔离环境
# 命名空间规划:
# - development: 开发环境
# - staging: 预发布环境
# - production: 生产环境
# - monitoring: 监控组件
# - ingress: 入口控制器
# 2. 设置默认资源配额
---
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
env: production
team: backend
练习 7:CI/CD 最佳实践
# GitHub Actions 示例
name: Deploy to Kubernetes
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build and Push Image
run: |
docker build -t my-app:${{ github.sha }} .
docker push my-app:${{ github.sha }}
- name: Deploy to K8s
run: |
kubectl set image deployment/my-app \
app=my-app:${{ github.sha }}
kubectl rollout status deployment/my-app
检查清单
生产环境检查清单
安全:
□ 使用非 root 用户
□ 只读文件系统
□ 网络策略
□ RBAC 配置
□ Secret 加密
资源:
□ 设置资源请求和限制
□ 配置 Resource Quota
□ 配置 Limit Range
□ 启用 HPA
部署:
□ 使用具体版本标签
□ 配置健康检查
□ 设置 PDB
□ 优雅终止
监控:
□ 暴露指标端点
□ 配置告警
□ 集中日志
□ 链路追踪
小结
| 领域 | 最佳实践 |
|---|---|
| 安全 | 非 root、最小权限、网络策略 |
| 资源 | 请求/限制、Quota、HPA |
| 部署 | Rolling Update、PDB、健康检查 |
| 配置 | ConfigMap、Secret、环境变量 |
| 监控 | Prometheus、Grafana、告警 |
| 组织 | 命名空间、RBAC、标签 |
练习编辑器
bash
Loading...