A Crash-Looping Pod Can't Be Exec'd Into, So Repair Its Volume from a One-Off Job
When an app writes a bad setting into its persistent volume and then crashes on startup, it enters CrashLoopBackOff. kubectl exec needs a running container, so you can't get a shell in to fix the file. Deleting the claim fixes the crash by destroying all the app's data. The repair that keeps the data is to stop the app, mount the same claim in a short-lived Job, patch the file there, and start the app again.
Why exec Doesn't Help
kubectl exec attaches to a container that is running. A crash-looping container lives for seconds between long back-off waits, so there is nothing to attach to most of the time. And when there is, the app may be in the middle of reading the broken file.
The Repair Job
- Stop the app, so that it releases the volume (a
ReadWriteOnceclaim can't be mounted by two pods on different nodes) and stops rewriting the file:kubectl scale deployment lazylibrarian -n media --replicas=0 - Run a Job that mounts the same claim and makes the change, printing the line before and after:
apiVersion: batch/v1 kind: Job metadata: {name: fix-lazylibrarian-config, namespace: media} spec: template: spec: restartPolicy: Never containers: - name: editor image: alpine:latest command: ["/bin/sh", "-c"] args: - | grep "Download_Dir" /config/config.ini sed -i 's|Download_Dir = /books|Download_Dir = /data/media/books|g' /config/config.ini grep "Download_Dir" /config/config.ini volumeMounts: [{name: config, mountPath: /config}] volumes: - name: config persistentVolumeClaim: {claimName: lazylibrarian-config} - Read the result, clean up, restart:
kubectl logs -n media -l job-name=fix-lazylibrarian-config, then delete the Job and scale the app back to one replica.
When Something Lighter Works
If the image has a shell, you can override the Deployment's command with sleep infinity for a while and exec into the pod normally. The Job is still the cleaner choice when the image has no shell or no editor, and, once its manifest is committed, it leaves a record of exactly what was changed.
References
- A PersistentVolumeClaim Requests Storage and a StorageClass Provisions It - why the data outlives the pod.
- Kubernetes Storage Failures Usually Start on the Host or the NAS - other volume problems behind crash loops.
- Kubernetes MOC - hub for Kubernetes notes.
- Kubernetes documentation: Jobs - run-to-completion pods.
- Kubernetes documentation: Pod lifecycle, container restarts - the back-off behind
CrashLoopBackOff.
Review cards
Flashcard Why can't `kubectl exec` be used to repair a crash-looping pod?
Because the container is not running long enough to attach to, and when it is, it may be in the middle of reading the broken file.
Flashcard Why do you scale a crash-looping Deployment to zero before repairing its volume?
So the app releases the volume (a ReadWriteOnce claim can't be mounted by pods on two nodes) and stops rewriting the broken file.