| name | kubernetes-patterns |
| description | Kubernetes 工作负载模式、资源管理、RBAC、probes、autoscaling、ConfigMap/Secret 处理,以及面向生产级部署的 kubectl 调试。 |
| metadata | {"origin":"ECC"} |
Kubernetes Patterns
面向可靠部署、管理和调试工作负载的生产级 Kubernetes 模式。
何时激活
- 编写 Kubernetes manifests(Deployments、Services、Ingress、Jobs)
- 配置 resource requests/limits、liveness/readiness probes
- 搭建 RBAC、namespaces 或 ServiceAccounts
- 在 K8s 中管理配置和 secrets
- 调试 CrashLoopBackOff、OOMKilled、pending pods 或 image pull errors
- 配置 HPA(Horizontal Pod Autoscaler)或 PodDisruptionBudgets
- 审查 K8s YAML 的安全或正确性
何时使用
同上方 何时激活。此别名满足仓库 skill-format 约定。任何编写、审查或调试 Kubernetes YAML 和工作负载时都可使用此技能。
工作方式
此技能提供可复制粘贴的生产级 YAML 模式和按任务组织的 kubectl 调试命令:
- Deployment 模板 — 完整配置的生产
Deployment,含 security context、rolling update 策略、三种 probe 类型、resource limits,以及从 ConfigMap/Secret 注入环境变量。
- Probes — startup vs liveness vs readiness 的决策表,含正确的
failureThreshold × periodSeconds 数学。
- Services & Ingress — ClusterIP、LoadBalancer 和带 cert-manager annotations 的 TLS Ingress 模式。
- ConfigMaps & Secrets —
envFrom、file-mount 和 external secrets 指引。
- 资源管理 — 按工作负载类型(web API、JVM、worker、sidecar)的 requests vs limits 经验规则。
- RBAC — 最小权限 ServiceAccount → Role → RoleBinding 链。
- HPA & PDB — Autoscaling 和 node-drain 安全配置。
- Jobs & CronJobs — 带正确
restartPolicy 的一次性和定时工作负载模式。
- kubectl cheatsheet — logs、exec、rollback、port-forward、dry-run 和常见错误诊断命令。
- 反模式与 checklist — 不要做什么,以及安全/可靠性/可观测性 checklist。
示例
完整可运行示例见下方 sections。快速参考:
Core Workload Patterns
Deployment — 生产模板
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: my-namespace
labels:
app: my-app
version: "1.0.0"
spec:
replicas: 3
selector:
matchLabels:
app: my-app
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: my-app
version: "1.0.0"
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1001
fsGroup: 1001
terminationGracePeriodSeconds: 30
containers:
- name: my-app
image: ghcr.io/org/my-app:1.0.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
protocol: TCP
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
startupProbe:
httpGet:
path: /health
port: 8080
failureThreshold: 30
periodSeconds: 5
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 0
periodSeconds: 30
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
failureThreshold: 2
envFrom:
- configMapRef:
name: my-app-config
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: my-app-secrets
key: db-password
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
Probes — Liveness, Readiness, Startup
理解每种 probe 何时使用很关键:
| Probe | 失败动作 | 用于 |
|---|
startupProbe | 启动慢则杀掉容器 | 慢启动应用(JVM、Python) |
livenessProbe | 重启容器 | 死锁 / 卡住进程检测 |
readinessProbe | 从 Service endpoints 移除 | 临时不可用(DB 重连) |
startupProbe:
httpGet:
path: /health
port: 8080
failureThreshold: 30
periodSeconds: 5
livenessProbe:
httpGet:
path: /health
port: 8080
periodSeconds: 30
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8080
periodSeconds: 10
failureThreshold: 2
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 60
Services and Ingress
Service 类型
apiVersion: v1
kind: Service
metadata:
name: my-app
namespace: my-namespace
spec:
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
protocol: TCP
type: ClusterIP
spec:
type: LoadBalancer
ports:
- port: 443
targetPort: 8080
带 TLS 的 Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-app
namespace: my-namespace
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
ingressClassName: nginx
tls:
- hosts:
- myapp.example.com
secretName: my-app-tls
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-app
port:
number: 80
ConfigMaps and Secrets
ConfigMap — 非敏感配置
apiVersion: v1
kind: ConfigMap
metadata:
name: my-app-config
namespace: my-namespace
data:
LOG_LEVEL: "info"
APP_ENV: "production"
MAX_CONNECTIONS: "100"
app.yaml: |
server:
port: 8080
timeout: 30s
volumes:
- name: config
configMap:
name: my-app-config
items:
- key: app.yaml
path: app.yaml
volumeMounts:
- name: config
mountPath: /etc/app
readOnly: true
Secrets — 敏感数据
kubectl create secret generic my-app-secrets \
--from-literal=db-password='s3cr3t' \
--namespace=my-namespace \
--dry-run=client -o yaml | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: my-app-secrets
namespace: my-namespace
type: Opaque
data:
db-password: czNjcjN0
重要: 原始 Kubernetes Secrets 只是 base64 编码,除非集群配置了加密,否则不是静态加密。生产环境用 Sealed Secrets 或 External Secrets Operator。
Resource Requests and Limits
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
经验规则:
| 工作负载类型 | CPU Request | Memory Request | 备注 |
|---|
| Web API | 100–250m | 128–256Mi | limits 设为 requests 的 2-4 倍 |
| Worker/consumer | 250–500m | 256–512Mi | memory limit = request 以保证可预测 |
| JVM 应用 | 500m–1 | 512Mi–2Gi | 在 -Xmx 之上留 JVM overhead |
| Sidecar | 10–50m | 32–64Mi | 保持最小 |
containers:
- name: app
image: myapp:latest
resources:
limits:
cpu: "2"
memory: "1Gi"
RBAC — Roles and ServiceAccounts
最小权限原则
两种模式,取决于应用是否调用 Kubernetes API:
模式 A — 应用不需要 Kubernetes API(大多数应用)
在 ServiceAccount 上禁用 token 自动挂载。不需要 Role/RoleBinding。
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-app-sa
namespace: my-namespace
automountServiceAccountToken: false
spec:
template:
spec:
serviceAccountName: my-app-sa
automountServiceAccountToken: false
模式 B — 应用需要 Kubernetes API(operators、controllers、config watchers)
启用 token,并只授予实际需要的权限。
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-app-sa
namespace: my-namespace
automountServiceAccountToken: true
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: my-app-role
namespace: my-namespace
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["secrets"]
resourceNames: ["my-app-secrets"]
verbs: ["get"]
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: my-app-rolebinding
namespace: my-namespace
subjects:
- kind: ServiceAccount
name: my-app-sa
namespace: my-namespace
roleRef:
kind: Role
apiGroup: rbac.authorization.k8s.io
name: my-app-role
spec:
template:
spec:
serviceAccountName: my-app-sa
Horizontal Pod Autoscaler (HPA)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
namespace: my-namespace
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
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
HPA 要求所有容器都设置 resources.requests——它按 current / request 计算 utilization。
PodDisruptionBudget (PDB)
防止 node drain 或滚动更新期间过多 pod 同时下线:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: my-app-pdb
namespace: my-namespace
spec:
minAvailable: 2
selector:
matchLabels:
app: my-app
Namespaces and Multi-Tenancy
kubectl create namespace my-namespace
kubectl apply -f - <<EOF
apiVersion: v1
kind: ResourceQuota
metadata:
name: my-namespace-quota
namespace: my-namespace
spec:
hard:
requests.cpu: "4"
requests.memory: 4Gi
limits.cpu: "8"
limits.memory: 8Gi
pods: "20"
EOF
Jobs and CronJobs
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
namespace: my-namespace
spec:
backoffLimit: 3
ttlSecondsAfterFinished: 3600
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: ghcr.io/org/my-app:1.0.0
command: ["python", "manage.py", "migrate"]
resources:
requests:
cpu: "100m"
memory: "256Mi"
apiVersion: batch/v1
kind: CronJob
metadata:
name: cleanup-job
namespace: my-namespace
spec:
schedule: "0 2 * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: cleanup
image: ghcr.io/org/cleanup:1.0.0
resources:
requests:
cpu: "50m"
memory: "64Mi"
kubectl Debugging Cheatsheet
kubectl get pods -n my-namespace
kubectl get pods -n my-namespace -o wide
kubectl describe pod <pod-name> -n my-namespace
kubectl logs <pod-name> -n my-namespace
kubectl logs <pod-name> -n my-namespace --previous
kubectl logs <pod-name> -n my-namespace -c <container>
kubectl exec -it <pod-name> -n my-namespace -- sh
kubectl exec -it <pod-name> -n my-namespace -- bash
kubectl top pods -n my-namespace
kubectl top nodes
kubectl rollout status deployment/my-app -n my-namespace
kubectl rollout history deployment/my-app -n my-namespace
kubectl rollout undo deployment/my-app -n my-namespace
kubectl rollout undo deployment/my-app --to-revision=2 -n my-namespace
kubectl scale deployment my-app --replicas=5 -n my-namespace
kubectl get events -n my-namespace --sort-by='.lastTimestamp'
kubectl port-forward pod/<pod-name> 8080:8080 -n my-namespace
kubectl port-forward svc/my-app 8080:80 -n my-namespace
kubectl apply -f deployment.yaml --dry-run=client
kubectl apply -f deployment.yaml --dry-run=server
诊断常见错误
kubectl logs <pod-name> --previous -n my-namespace
kubectl describe pod <pod-name> -n my-namespace
kubectl describe pod <pod-name> -n my-namespace
kubectl describe pod <pod-name> -n my-namespace
kubectl describe pod <pod-name> -n my-namespace | grep -A5 "Last State"
反模式
image: myapp:latest
image: ghcr.io/org/myapp:1.4.2
image: ghcr.io/org/myapp@sha256:abc123...
securityContext: {}
securityContext:
runAsNonRoot: true
runAsUser: 1001
containers:
- name: app
image: myapp:1.0.0
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
apiVersion: v1
kind: ConfigMap
data:
DB_PASSWORD: "mysecretpassword"
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
roleRef:
kind: ClusterRole
name: cluster-admin
spec:
minAvailable: 0
spec:
restartPolicy: Always
最佳实践 Checklist
安全
可靠性
可观测性
相关技能
docker-patterns — 多阶段 Dockerfiles 和镜像安全
deployment-patterns — CI/CD pipelines、rollback 策略、health check endpoints
security-review — 更广泛的安全加固上下文
git-workflow — GitOps 与 K8s 集成(ArgoCD / Flux 模式)