CKA 部署与服务实验 #2
发布: (2026年1月9日 GMT+8 07:38)
4 min read
原文: Dev.to
Source: Dev.to
全局规则
- 不要 使用
kubectl edit - 不要 除非被要求,否则不要重新创建资源
- 使用
kubectl patch/set/scale/rollout来修复问题 - 必须使用命名空间
- 将此视为真实的 CKA 考试
基线(在每台机器上运行)
步骤 0 – 启动集群
minikube start --driver=docker
kubectl create namespace cka-lab
kubectl config set-context --current --namespace=cka-lab
部署应用
kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 4
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
EOF
暴露应用
kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
name: web-svc
spec:
selector:
app: web
ports:
- port: 80
targetPort: 80
type: ClusterIP
EOF
产生流量
kubectl run traffic --image=busybox -it --rm -- sh
在 Pod 内部:
while true; do
wget -qO- web-svc
echo "-----"
sleep 1
done
任务
修复部署策略
kubectl patch deployment web-app -p '
{
"spec": {
"strategy": {
"type": "RollingUpdate",
"rollingUpdate": {
"maxUnavailable": 4,
"maxSurge": 0
}
}
}
}'
- 镜像更新期间不出现停机
- 流量循环永不停止
- 至少始终有一个 Pod 可用
模拟镜像拉取失败
kubectl set image deployment/web-app nginx=nginx:doesnotexist
将部署恢复到健康状态(不删除)
kubectl patch deployment web-app --type=json -p='[
{
"op": "remove",
"path": "/spec/template/spec/containers/0/readinessProbe"
}
]'
- 所有 Pod Running,没有
CrashLoopBackOff - 流量循环保持稳定
确保流量仅发送到就绪的 Pod(不重启集群)
将 Service 选择器改为错误的值:
kubectl patch svc web-svc -p '
{
"spec": {
"selector": {
"app": "wrong"
}
}
}'
恢复正确的选择器(不重新创建 Service)
kubectl patch svc web-svc -p '
{
"spec": {
"selector": {
"app": "web"
}
}
}'
- Endpoints 重新填充,流量恢复
部署金丝雀版本
kubectl create deployment web-app-canary --image=nginx:1.27 --replicas=1
kubectl label deployment web-app-canary track=canary
- 金丝雀与稳定工作负载一起接收流量
- 不重新创建 Service
立即删除有问题的金丝雀
kubectl delete deployment web-app-canary
- 稳定版本继续无中断地提供流量
暂停滚动更新,更新镜像,然后完成滚动更新
kubectl rollout pause deployment web-app
kubectl set image deployment/web-app nginx=nginx:1.26
- 找出滚动更新卡住的原因
- 完成部署:
kubectl rollout resume deployment web-app
- 新镜像已完整部署,滚动更新不再暂停
通过 NodePort 暴露 Service(不重新创建)
kubectl patch svc web-svc -p '
{
"spec": {
"type": "NodePort"
}
}'
- 可通过分配的 NodePort 在浏览器中访问应用
缩容至 0 并恢复 Service
kubectl scale deployment web-app --replicas=0
恢复原始副本数(不要 重新创建 Pod):
kubectl scale deployment web-app --replicas=4
- Pod 运行,流量恢复
清理
kubectl delete namespace cka-lab
- 命名空间必须为空
kubectl get all
# → No resources found