K8s共享Volume的Pod故障排查:fortune-cont容器CrashLoopBackOff
排查Kubernetes共享Volume的Pod中容器CrashLoopBackOff问题
问题描述
实践《Kubernetes in Action》中6.1. 包含两个共享Volume的Pod: fortune-pod.yaml示例时,Pod内fortune-cont容器无法正常运行,处于CrashLoopBackOff状态。
容器日志提示
Defaulted container "fortune-cont" out of: fortune-cont, web-server
Pod事件
Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 40m default-scheduler Successfully assigned book/vol-1-fd556f5dc-8ggj6 to minikube Normal Pulled 40m kubelet Container image "nginx:alpine" already present on machine Normal Created 40m kubelet Created container web-server Normal Started 40m kubelet Started container web-server Normal Created 39m (x4 over 40m) kubelet Created container fortune-cont Normal Started 39m (x4 over 40m) kubelet Started container fortune-cont Normal Pulled 38m (x5 over 40m) kubelet Container image "xxxx/fortune:v1" already present on machine Warning BackOff 25s (x188 over 40m) kubelet Back-off restarting failed container
Deployment配置
apiVersion: apps/v1 kind: Deployment metadata: name: vol-1 namespace: book spec: replicas: 1 selector: matchLabels: name: fortune-vol-1 type: volume template: metadata: labels: name: fortune-vol-1 type: volume spec: containers: - image: ****/fortune:v1 name: fortune-cont volumeMounts: - name: html mountPath: /var/htdocs - image: nginx:alpine name: web-server volumeMounts: - name: html mountPath: /usr/share/nginx/html readOnly: true ports: - containerPort: 80 protocol: TCP volumes: - name: html emptyDir: {}
Pod关键状态信息
Containers: fortune-cont: Image: prav33n/fortune:v1 State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Restart Count: 17 Mounts: /var/htdocs from html (rw) web-server: State: Running Ready: True
问题根源
fortune-cont容器退出码为0(正常退出),但容器启动后立即完成一次性任务并退出,Kubernetes会因容器退出反复重启它,进而触发CrashLoopBackOff。这是因为当前镜像仅执行单次fortune命令,而非保持长期运行的进程,不符合Kubernetes对容器持续运行的要求。
解决步骤
1. 修改容器启动命令,维持进程持续运行
更新Deployment中fortune-cont的配置,添加循环命令定期生成文件并保持容器存活:
containers: - image: prav33n/fortune:v1 name: fortune-cont command: ["/bin/sh"] args: ["-c", "while true; do fortune > /var/htdocs/index.html; sleep 30; done"] volumeMounts: - name: html mountPath: /var/htdocs
该配置会让容器每隔30秒生成新的fortune文本到共享Volume的index.html文件中,同时保持进程持续运行。
2. 应用配置更新
执行命令生效修改:
kubectl apply -f <你的Deployment文件名>.yaml -n book
3. 验证Pod状态
等待片刻后检查Pod状态:
kubectl get pods -n book
确认fortune-cont容器状态变为Running,Pod整体状态变为Ready。
4. 验证功能
通过端口转发访问Nginx服务,确认能看到生成的fortune文本:
# 替换<pod-name>为实际Pod名称 kubectl port-forward <pod-name> 8080:80 -n book # 用curl访问或打开浏览器访问 http://localhost:8080 curl http://localhost:8080
补充说明
如果prav33n/fortune:v1镜像未包含fortune命令或sh终端,需先检查镜像内容,或参考《Kubernetes in Action》示例,基于alpine镜像安装fortune包并编写启动脚本构建镜像。
内容的提问来源于stack exchange,提问作者Praveen
相关产品推荐
相关产品推荐

