Symptom
A task that uses KubernetesPodOperator (KPO) fails. The Airflow task log shows one of these:
Pod took too long to startor a startup timeout after the pod spent a long time inPending.- The pod never ran your code: the log shows container waiting reasons such as
ErrImagePull,ImagePullBackOfforCreateContainerConfigError. - The task ran for a while and then failed with no Python traceback and the pod ended with exit code 137.
- The task succeeded or failed in Airflow, but pods are piling up in the namespace.
Airflow only shows you part of the story. The Kubernetes events and the pod's container status hold the real reason. Start there.
Find the pod behind the task
KPO labels the pods it creates with the DAG, task and run. Label values are sanitised to be valid Kubernetes labels (lowercased, special characters replaced, long values truncated), so match on what you see rather than the raw DAG ID.
NS=airflow-jobs # the namespace your KPO tasks run in
# All KPO-created pods, newest last
kubectl get pods -n $NS -l kubernetes_pod_operator=True \
--sort-by=.metadata.creationTimestamp -L dag_id,task_id,try_number
# Narrow to one task
kubectl get pods -n $NS -l dag_id=sales_daily,task_id=transform -o wide
If the pod is already deleted, the task log usually prints the pod name near the top (Creating pod ...). Events survive for a while after the pod is gone (one hour by default on most clusters):
kubectl get events -n $NS --field-selector involvedObject.name=<pod-name> \
--sort-by=.lastTimestamp
For a live or retained pod, three commands answer most questions:
kubectl describe pod <pod-name> -n $NS # events, conditions, node
kubectl get pod <pod-name> -n $NS \
-o jsonpath='{.status.containerStatuses[*].state}{"\n"}{.status.containerStatuses[*].lastState}{"\n"}'
kubectl logs <pod-name> -n $NS -c base --previous # KPO's main container is named "base"
Symptom → cause → fix
| What you see | Likely cause | Fix |
|---|---|---|
Pending, event FailedScheduling ... Insufficient cpu/memory | Requests larger than any node's free capacity, or cluster autoscaler not adding nodes | Lower requests, add a node pool that fits, check autoscaler logs |
Pending, event didn't match Pod's node affinity/selector or untolerated taint | node_selector, affinity or tolerations point at nodes that don't exist or are tainted | Fix the selector or add the toleration |
Pending, persistentvolumeclaim ... not found or unbound | Volume or PVC missing, or zone mismatch with the node | Create the PVC, check its storage class and zone |
ErrImagePull / ImagePullBackOff | Wrong tag, private registry without credentials, registry blocked by egress rules | Check image name, add image_pull_secrets, test the pull from a node |
CreateContainerConfigError | Referenced Secret or ConfigMap (or a key in it) does not exist in the namespace | Create it in the pod's namespace; secrets are not shared across namespaces |
Exit code 137, reason: OOMKilled | Container hit its memory limit | Raise the memory limit or reduce memory use |
| Exit code 137, no OOMKilled, node shows eviction | Node pressure eviction or spot/preemptible node reclaimed | Set requests close to real usage, use on-demand nodes for critical tasks |
Forbidden creating pods in the task log | Airflow's service account lacks RBAC in the target namespace | Grant create/get/list/watch/delete on pods, pods/log and pods/exec |
Hundreds of Completed or Error pods left behind | on_finish_action set to keep pods, or workers died mid-task | Change the action, clean up by label |
Pods stuck in Pending
Read the Events section of kubectl describe pod. The scheduler message says exactly which constraint failed, for example 0/6 nodes are available: 3 Insufficient memory, 3 node(s) had untolerated taint {dedicated: gpu}.
Check what nodes actually have free:
kubectl describe nodes | grep -A 8 "Allocated resources"
kubectl top nodes
If the cluster autoscaler should have added a node, look at its status. Names vary by distribution; on many clusters:
kubectl -n kube-system get configmap cluster-autoscaler-status -o yaml
kubectl get events -n $NS --field-selector reason=NotTriggerScaleUp
A NotTriggerScaleUp event means no node group could fit the pod even after scaling. Usually the request is bigger than the largest node type, or the selector matches no node group.
Give KPO a startup timeout that covers a cold node scale-up. Set it explicitly rather than relying on the provider default:
from airflow.providers.cncf.kubernetes.operators.pod import KubernetesPodOperator
from kubernetes.client import models as k8s
transform = KubernetesPodOperator(
task_id="transform",
name="sales-transform",
namespace="airflow-jobs",
image="myregistry.azurecr.io/etl/transform:1.4.2",
startup_timeout_seconds=600, # time allowed for Pending -> Running
container_resources=k8s.V1ResourceRequirements(
requests={"cpu": "1", "memory": "2Gi"},
limits={"memory": "4Gi"},
),
node_selector={"agentpool": "etl"},
on_finish_action="delete_succeeded_pod",
)
Tip
On older provider versions the import path was
airflow.providers.cncf.kubernetes.operators.kubernetes_podand resources were passed as aresourcesdict. Check your installed provider version withpip show apache-airflow-providers-cncf-kubernetesbefore copying examples.
ImagePullBackOff and config errors
Get the exact pull error from the events. not found means a wrong tag. unauthorized or 401 means credentials. i/o timeout means network or egress rules.
kubectl get events -n $NS --field-selector involvedObject.name=<pod-name>,reason=Failed
For a private registry, create a pull secret in the pod's namespace and reference it:
kubectl create secret docker-registry regcred -n $NS \
--docker-server=myregistry.azurecr.io \
--docker-username=<user> --docker-password=<token>
image_pull_secrets=[k8s.V1LocalObjectReference("regcred")],
On AKS, EKS and OKE you can instead grant the node identity pull rights on the registry, for example az aks update -n <cluster> -g <rg> --attach-acr <acr-name>.
For CreateContainerConfigError, kubectl describe pod names the missing Secret or key. Confirm it exists in the same namespace as the pod:
kubectl get secret <name> -n $NS -o jsonpath='{.data}' | head -c 300
Warning
Avoid
:latesttags in KPO tasks. A retry can pull a different image from the first try, andimagePullPolicy: Alwaysturns every registry blip into a task failure. Pin a version tag or digest.
Exit code 137 and OOMKilled
Exit code 137 means the process got SIGKILL. Confirm whether the kernel OOM killer did it:
kubectl get pod <pod-name> -n $NS \
-o jsonpath='{.status.containerStatuses[?(@.name=="base")].lastState.terminated.reason}{"\n"}'
If it says OOMKilled, the container exceeded its memory limit. Check the real peak before changing anything. If metrics-server is installed, watch a rerun with kubectl top pod <pod-name> -n $NS --containers. Then either:
- raise
limits.memory, and raiserequests.memorywith it so the scheduler places the pod on a node that can actually hold it, or - reduce memory use: process in chunks, stream files instead of loading them whole, or set the JVM or Python worker heap below the container limit.
If the reason is empty or Error and the node shows evictions or the node itself disappeared, the pod was evicted or the spot node was reclaimed:
kubectl get events -A --field-selector reason=Evicted --sort-by=.lastTimestamp | tail
Set retries with a delay on these tasks (retries=2, retry_delay=timedelta(minutes=5)) and keep critical ones off spot nodes.
Orphaned and leftover pods
on_finish_action controls cleanup after a normal finish. Valid values are delete_pod, delete_succeeded_pod and keep_pod. delete_succeeded_pod is a good production default: failed pods stay for debugging, successful ones go. on_kill_action controls what happens when the task is killed or marked failed from the UI.
Pods can still be orphaned when a worker or scheduler dies while the pod runs. Find and remove finished KPO pods older than you need:
# List finished KPO pods
kubectl get pods -n $NS -l kubernetes_pod_operator=True \
--field-selector=status.phase!=Running,status.phase!=Pending
# Delete succeeded ones
kubectl delete pods -n $NS -l kubernetes_pod_operator=True \
--field-selector=status.phase=Succeeded
Caution
Don't delete
RunningKPO pods to "clean up". If the task is still active in Airflow, you kill the job mid-write. Check the task state in Airflow first, and mark it failed there soon_kill_actionruns.
RBAC errors
If the task log shows Forbidden when creating or reading pods, check what Airflow's service account can do in the target namespace:
SA=system:serviceaccount:airflow:airflow-worker # names vary by chart and install
for verb in create get list watch delete; do
echo -n "pods $verb: "; kubectl auth can-i $verb pods -n $NS --as=$SA
done
kubectl auth can-i get pods/log -n $NS --as=$SA
KPO needs to create, watch and delete pods, read pods/log, and create pods/exec if you use XCom push from the sidecar (do_xcom_push=True).
Prevent it next time
- Pin image tags and set
startup_timeout_secondsto cover node scale-up time. - Always set memory requests and limits from measured usage, not guesses.
- Use
on_finish_action="delete_succeeded_pod"and a scheduled cleanup for old failed pods. - Run critical tasks in a dedicated node pool with taints and matching tolerations so other workloads can't starve them.
- Alert on pods in
Pendingfor more than a few minutes in the KPO namespace, and onOOMKilledevents. - Keep a namespace
ResourceQuotaandLimitRangeso one DAG can't consume the whole cluster.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get