关于 kubernetes
面向编写和运维 Kubernetes 工作负载的技能,涵盖部署配置、常用 kubectl 操作、生产准备与故障排查。还提供安全、资源管理和健康检查方面的实践建议。
主要功能
- 01Deployment、Service 等配置示例
- 02常用 kubectl 命令
- 03生产环境准备清单
- 04故障诊断与处理建议
- 05安全与资源管理实践
适用场景
- 01编写 Kubernetes 部署清单
- 02排查 Pod 与服务异常
- 03检查生产环境部署准备情况
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill kubernetes安装后在 Claude Code 中输入/kubernetes确认已加载。
附带文件quick-ref/kubectl.mdquick-ref/resources.md
详细介绍
Kubernetes 核心知识
深入了解:使用
mcp__documentation__fetch_docs并指定技术:kubernetes,获取完整文档。
Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
labels:
app: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:1.0.0
ports:
- containerPort: 3000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: myapp-secrets
key: database-url
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 3000
Service
apiVersion: v1
kind: Service
metadata:
name: myapp
spec:
selector:
app: myapp
ports:
- port: 80
targetPort: 3000
type: ClusterIP
---
# Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp
port:
number: 80
ConfigMap 和 Secret
apiVersion: v1
kind: ConfigMap
metadata:
name: myapp-config
data:
LOG_LEVEL: "info"
API_URL: "https://api.example.com"
---
apiVersion: v1
kind: Secret
metadata:
name: myapp-secrets
type: Opaque
data:
database-url: cG9zdGdyZXM6Ly8uLi4= # base64
常用命令
kubectl apply -f deployment.yaml
kubectl get pods
kubectl logs pod-name
kubectl exec -it pod-name -- sh
kubectl scale deployment myapp --replicas=5
kubectl rollout status deployment/myapp
kubectl rollout undo deployment/myapp
不适用此技能的场景
以下情况请跳过此技能:
- 使用多个容器搭建本地开发环境 — 请使用
docker-compose技能 - 创建容器镜像 — 请使用
docker技能 - 管理 CI/CD 流水线 — 请使用
github-actions技能 - 运行单服务器部署(VPS)— Docker Compose 可能更简单
- 使用将 K8s 抽象化的托管容器服务(AWS Fargate、Google Cloud Run)
反模式
| 反模式 | 问题 | 解决方案 |
|---|---|---|
| 未设置资源限制 | 资源耗尽、邻居噪声 | 始终设置 resources.requests 和 limits |
| 以 root 身份运行 | 安全漏洞 | 设置 securityContext.runAsNonRoot: true |
| 未设置就绪探针 | 流量被发送到正在启动的 Pod | 添加 readinessProbe,实现零停机 |
使用 latest 镜像标签 | 部署结果不可预测 | 固定特定版本,如 myapp:v1.2.3 |
| 在 ConfigMaps 中存储密钥 | 敏感数据暴露 | 使用 Secrets、External Secrets 或 Sealed Secrets |
| 未设置 Pod 中断预算 | 节点维护期间发生停机 | 添加设置了 minAvailable 的 PDB |
| 关键服务仅有一个副本 | 单点故障 | 至少使用 2 个副本并设置反亲和性 |
| 未设置网络策略 | 所有 Pod 都能相互通信 | 使用 NetworkPolicy 限制流量 |
| 缺少健康检查 | 不健康的 Pod 仍留在轮换中 | 添加 livenessProbe 和 readinessProbe |
| maxUnavailable = maxSurge = 0 | 发布卡住 | 滚动更新时至少将其中一个设为大于 0 |
快速故障排查
| 问题 | 诊断 | 修复方法 |
|---|---|---|
Pod 卡在 Pending | 资源不足 | 检查 kubectl describe pod,添加节点或降低请求量 |
Pod 处于 CrashLoopBackOff 状态 | 容器立即退出 | 检查日志:kubectl logs pod-name --previous |
ImagePullBackOff | 无法拉取镜像 | 确认镜像存在,并检查 imagePullSecrets |
| Service 无法访问 | 选择器错误或没有端点 | 检查 kubectl get endpoints service-name |
| 就绪探针失败 | 应用未能及时就绪 | 增大 initialDelaySeconds,或修复应用启动问题 |
状态为 OOMKilled | 超出内存限制 | 增大 resources.limits.memory |
| Ingress 返回 404 | 路径错误或找不到服务 | 确认 Ingress 规则正确,且后端服务存在 |
| ConfigMap 更改未生效 | Pod 未重启 | 触发滚动更新:更改注解或镜像 |
0/3 nodes available | 资源限制或污点 | 检查节点状态:kubectl describe nodes |
| 持久卷未挂载 | PVC 未绑定或存储类错误 | 检查 PVC 状态:kubectl get pvc |
生产环境就绪情况
安全配置
# Pod Security Context
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
template:
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
containers:
- name: myapp
image: myapp:1.0.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
# Network Policy - Restrict traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: myapp-network-policy
spec:
podSelector:
matchLabels:
app: myapp
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 3000
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
密钥管理
# External Secrets Operator (recommended)
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: myapp-secrets
spec:
refreshInterval: 1h
secretStoreRef:
name: vault-backend
kind: ClusterSecretStore
target:
name: myapp-secrets
data:
- secretKey: database-url
remoteRef:
key: myapp/database
property: url
# Sealed Secrets (alternative)
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
name: myapp-secrets
spec:
encryptedData:
database-url: AgBy3i4OJSWK+PiTySYZZA9rO43cGDEq...
资源管理
# Proper resource limits
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: myapp
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "1000m"
# Vertical Pod Autoscaler can optimize these
# Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: myapp-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp
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
# Pod Disruption Budget
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: myapp-pdb
spec:
minAvailable: 1 # Or maxUnavailable: 1
selector:
matchLabels:
app: myapp
健康探针
# Comprehensive health probes
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: myapp
# Startup probe (for slow-starting apps)
startupProbe:
httpGet:
path: /health
port: 3000
failureThreshold: 30
periodSeconds: 10
# Liveness probe (restart if unhealthy)
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 0
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
# Readiness probe (traffic routing)
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 0
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
滚动更新
# Safe rolling update strategy
apiVersion: apps/v1
kind: Deployment
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # Max extra pods during update
maxUnavailable: 0 # Zero downtime
template:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: myapp
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 10"]
监控与可观测性
# ServiceMonitor for Prometheus
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: myapp
spec:
selector:
matchLabels:
app: myapp
endpoints:
- port: http
path: /metrics
interval: 30s
监控指标
| 指标 | 告警阈值 |
|---|---|
| Pod 重启次数 | 15 分钟内 > 3 次 |
| CPU 利用率 | 持续 > 80% |
| 内存利用率 | > 85% |
| Pod 等待时间 | > 5 分钟 |
| 失败的部署 | > 0 |
| 证书到期时间 | < 30 天 |
使用 TLS 的 Ingress
# Ingress with cert-manager TLS
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
ingressClassName: nginx
tls:
- hosts:
- myapp.example.com
secretName: myapp-tls
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp
port:
number: 80
检查清单
- Pod 安全上下文(非 root、只读文件系统)
- 已定义网络策略
- 通过 External Secrets/Sealed Secrets 管理机密
- 已设置资源请求和限制
- 已配置 HPA 以实现自动扩缩容
- 已配置 PDB 以确保高可用性
- 存活、就绪和启动探针
- 滚动更新策略(零停机)
- 优雅关闭(preStop 钩子)
- 通过 cert-manager 管理 TLS 证书
- 已导出 Prometheus 指标
- Pod 反亲和性以分散分布
- 已正确限定 RBAC 范围
- 镜像拉取策略::latest 使用 Always,否则使用 IfNotPresent
参考文档
评论
支持 Markdown