GKE Workload Troubleshooting

GKE Workload Troubleshooting

Diagnoses failing GKE workloads such as CrashLoopBackOff, OOMKilled and ImagePullBackOff from logs and events, and proposes fixes without making live changes.

Skill files2 files

references/

SKILL.md364 lines
1
---
2
name: gke-workload-troubleshooting
3
metadata:
4
version: "1.0.1"
5
category: Containers
6
description: >-
7
Diagnoses GKE workload failures (CrashLoopBackOff, OOMKilled, ImagePullBackOff, Pending, etc.) via logs and events. Use when pods fail to start or crash repeatedly. Don't use for GKE cluster infrastructure provisioning, node pool creation, or non-Kubernetes Google Cloud services.
8
---
9
10
# GKE Workload Troubleshooting Skill
11
12
Use this skill to systematically diagnose and resolve failures in application
13
workloads deployed in GKE clusters. This skill operates non-interactively and
14
enforces a read-only diagnostics boundary: it only **proposes** fixes — whether
15
Kubernetes manifest/config patches or Google Cloud changes (for example `gcloud`
16
IAM bindings or node-pool recreation) — and never executes live mutations
17
itself.
18
19
## Attribution
20
21
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
22
MUST read [Usage Attribution](references/attribution.md). For commands executed
23
directly in the terminal (never in generated scripts, Terraform, or user code),
24
prefix `gcloud` with
25
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gke-workload-troubleshooting)"`
26
and append `agent-skills/1.0 (skill:gke-workload-troubleshooting)` to `User-Agent` headers.
27
28
## 🔍 Diagnostic Workflow
29
30
### Step 0: Non-Interactive Context Discovery & Time Window Definition
31
32
1. **Parameter Extraction**: Extract required context (`project_id`,
33
`cluster_name`, `cluster_location`, `workload_name`, `workload_namespace`)
34
non-interactively from the user prompt, active `SETTINGS.md`, or active
35
environment defaults:
36
37
- Default `workload_namespace` to `default` if omitted.
38
- Infer missing cluster parameters from active environment (`kubectl
39
config current-context` or `gcloud config get-value project`).
40
- Prioritize non-interactive context discovery from prompts and
41
environment defaults to ensure autonomous execution flow.
42
43
2. **Cluster Credentials & Fallback Mode**:
44
45
- Attempt credential fetch: `gcloud container clusters get-credentials
46
{cluster_name} --region/--zone {cluster_location}`
47
- **Fallback / Dry-Run Mode**: If the cluster is unreachable,
48
non-existent, or live command execution fails (such as in sandboxed
49
evaluations, dry-run mode, or offline analysis):
50
- Limit retry attempts to avoid resource exhaustion and context
51
overflow in unreachable cluster scenarios.
52
- Immediately present the exact sequence of `kubectl` diagnostic
53
commands for the human operator to run.
54
- Synthesize the root cause analysis and output the proposed GitOps
55
manifest fix based on the reported symptoms.
56
57
3. **Time Handling & Fallbacks**:
58
59
- **Determine Issue Timestamp ({issue_time})**:
60
- **Specific Time Provided**: If the user provides a specific
61
timestamp, use it as `{issue_time}`.
62
- **Relative Time Provided (e.g., "5 minutes ago")**: Dynamically
63
calculate the corresponding UTC timestamp based on current system
64
time, and use it as `{issue_time}`.
65
- **No Time Provided (Default)**: Use current system time as
66
`{issue_time}`.
67
- **Window Calculation**: Center a 1-hour query window around
68
`{issue_time}` (`start_time` = `{issue_time} - 30m`, `end_time` =
69
`{issue_time} + 30m`).
70
71
--------------------------------------------------------------------------------
72
73
### Step 1: Analyze Pod Status and Conditions
74
75
Inspect the workload's active pod states and controller status.
76
77
**Diagnostic Commands:**
78
79
```bash
80
# 1. Inspect the deployment's actual selector labels:
81
kubectl get deployment {workload_name} -n {workload_namespace} -o jsonpath='{.spec.selector.matchLabels}'
82
# 2. Query the pods using the returned labels, for example:
83
kubectl get pods -l {selector_labels} -n {workload_namespace}
84
kubectl get deploy/{workload_name} -n {workload_namespace} -o yaml
85
```
86
87
#### Diagnostic Decision Tree:
88
89
- **Phase: Pending**:
90
- The Pod cannot schedule on any node. Proceed directly to **Step 2 (Query
91
Namespace Events)**.
92
- **State: CrashLoopBackOff / Error**:
93
94
- The container boots but exits repeatedly; the `kubelet` restarts it with
95
an increasing back-off delay of up to five minutes. First read the
96
terminated **reason** and **exit code**:
97
98
```bash
99
kubectl describe pod {pod_name} -n {workload_namespace}
100
kubectl get pod {pod_name} -n {workload_namespace} -o jsonpath='{.status.containerStatuses[*].lastState.terminated}'
101
```
102
103
- **Reason: OOMKilled (Exit Code 137)**: The container's memory limit was
104
reached. Proceed to **Step 3 (Inspect Logs) → OOM Analysis** to classify
105
container-level vs node-level, then **Step 5** to propose fixes.
106
- **Exit Code 0 (successful exit)**: Unexpected for a long-running
107
Deployment/StatefulSet — `restartPolicy: Always` restarts the finished
108
process, creating the loop. Common causes: the `command`/`entrypoint`
109
does not start a persistent process, a worker exits on an empty queue,
110
or a missing/invalid config (e.g., an unattached or mis-keyed
111
`ConfigMap` volume) makes the app exit cleanly. Proceed to **Step 3
112
(Inspect Logs)**.
113
- **Exit Code 128**: Invalid `command`/`entrypoint` — the executable path
114
is wrong or absent in the image. Verify the container command in the
115
manifest.
116
- **Exit Code 1 or other non-zero**: The application crashed —
117
configuration errors, missing/invalid env vars or config files,
118
unreachable dependencies, or auth failures (`401`/`403`) on Google Cloud
119
calls (check the Pod's IAM / Workload Identity Federation). Proceed
120
directly to **Step 3 (Inspect Logs)**.
121
- If the exit code looks healthy but the container keeps restarting,
122
suspect a **liveness probe failure** (see Step 3).
123
124
- **State: ImagePullBackOff / ErrImagePull**:
125
126
- The kubelet cannot pull the container image. `ImagePullBackOff` means it
127
keeps retrying with back-off; `ErrImagePull` is a general,
128
non-recoverable pull error. Related statuses: `InvalidImageName`,
129
`RegistryUnavailable`, `SignatureValidationFailed`, `ImageInspectError`.
130
Proceed to **Step 2 (Query Namespace Events)** to read the exact pull
131
error message.
132
133
- **State: ContainerCreating**:
134
135
- The container is blocked during volume mount, networking setup, or image
136
pulling. Proceed directly to **Step 2 (Query Namespace Events)**.
137
138
--------------------------------------------------------------------------------
139
140
### Step 2: Query Namespace Events
141
142
Look for infrastructure, volume, image, or scheduling alerts in GKE.
143
144
**Diagnostic Command:**
145
146
```bash
147
kubectl get events -n {workload_namespace} --sort-by='.metadata.creationTimestamp'
148
# Or query Cloud Logging for historical GKE events within the time window:
149
gcloud logging read "resource.type=\"k8s_cluster\" AND logName=\"projects/{project_id}/logs/events\" AND jsonPayload.involvedObject.namespace=\"{workload_namespace}\"" --start-time="{start_time}" --end-time="{end_time}" --project="{project_id}"
150
# Or query specifically for image pull failures within the time window:
151
gcloud logging read 'log_id("events") AND resource.type="k8s_pod" AND resource.labels.cluster_name="{cluster_name}" AND jsonPayload.message=~"Failed to pull image"' --project="{project_id}"
152
```
153
154
*Note: Retrieve the sorted events list and manually inspect the event timestamps
155
(CreationTimestamp/LastSeen) to identify failures occurring within the
156
`{start_time}` and `{end_time}` window.*
157
158
#### Signature Identifiers:
159
160
- **`FailedScheduling`**: Node resource exhaustion. Look for messages like
161
`0/3 nodes are available: 3 Insufficient memory.` or missing node affinity
162
tolerations (e.g. Spot VM taints).
163
- **`FailedMount`**:
164
- Missing PersistentVolumeClaim (`PVC`).
165
- Missing Secret (`Secret "{secret_name}" not found`).
166
- Missing ConfigMap (`ConfigMap "{configmap_name}" not found`).
167
- **`Failed` / `BackOff` (Image Pull)**: First read the exact event message
168
(`Failed to pull image "IMAGE": ...`) and triage by what it actually says.
169
Do **not** jump to IAM / node service-account investigation unless the
170
message is genuinely a permission or authentication error.
171
172
- **Wrong image name/tag — start here** (`not found`, `manifest unknown`,
173
`InvalidImageName`): the most common cause — the tag or path is wrong,
174
or the image was deleted, frequently introduced by a recent deployment
175
change.
176
* Identify the failing container image name and the invalid tag.
177
* Check the Git history for the last known working image tag: `git log
178
-p -S "{image_name}" -- {manifest_file_path}` (or run `git log` on
179
the folder containing manifests).
180
* Propose reverting the image tag to the last working version (or
181
correcting the tag) in the manifest patch.
182
- **Permission / authentication errors only** (the message contains `403
183
Forbidden` / `denied`, or `401 Unauthorized` / `unauthorized`): the node
184
cannot authorize or authenticate to the registry. Pursue the checks
185
below **only** when the message matches.
186
187
* **`403 Forbidden` (authorization)** — the node pool service account
188
(or the imagePullSecret's service account) is missing registry read
189
access. **Suggest** granting it by presenting the following command
190
for the user to review and run; do not execute it. For **Artifact
191
Registry**:
192
193
```bash
194
gcloud artifacts repositories add-iam-policy-binding {repository} \
195
--location={repo_location} \
196
--member="serviceAccount:{node_service_account_email}" \
197
--role="roles/artifactregistry.reader"
198
```
199
200
For **Container Registry (`gcr.io`)**, grant
201
`roles/storage.objectViewer` on the backing bucket (or the Artifact
202
Registry role if `gcr.io` was migrated). Also check that any **VPC
203
Service Controls** perimeter allows Artifact Registry.
204
* **`401 Unauthorized` (authentication)** — the node service account
205
is disabled or the node lacks the required OAuth scope:
206
207
```bash
208
gcloud container clusters describe {cluster_name} --location={cluster_location} \
209
--format="table(nodePools.name,nodePools.config.serviceAccount)"
210
gcloud iam service-accounts list \
211
--filter="email:{node_service_account_email} AND disabled:true" --project={project_id}
212
gcloud compute instances describe {node_name} --zone={node_zone} \
213
--format="flattened(serviceAccounts[].scopes)"
214
```
215
216
Scopes must include `devstorage.read_only` or `cloud-platform`
217
(provided by `gke-default`). Nodes are immutable, so **suggest**
218
recreating the node pool with `--scopes="gke-default"` if the scope
219
is missing — present it as a proposed command for the user to run,
220
do not execute it.
221
* **Private / self-hosted registry**: ensure a valid `imagePullSecret`
222
exists and is referenced by the Deployment.
223
- **Other statuses**: `RegistryUnavailable` / `i/o timeout` / DNS `server
224
misbehaving` → registry network path (DNS, firewall egress, Google API
225
connectivity); `exec format error` or a deprecated schema-1 image →
226
architecture/schema mismatch.
227
228
--------------------------------------------------------------------------------
229
230
### Step 3: Inspect Application Logs
231
232
Extract exceptions and stack traces from the application runtime.
233
234
**Diagnostic Commands:**
235
236
```bash
237
# Check current active log stream (handles multi-container pods)
238
kubectl logs {pod_name} -n {workload_namespace} --all-containers --tail=100
239
240
# Check logs from previously terminated container instances (handles multi-container pods)
241
kubectl logs {pod_name} -n {workload_namespace} --all-containers -p --tail=100
242
```
243
244
#### Signature Identifiers:
245
246
- **Out-of-Memory (OOM) Analysis**: First confirm and classify the kill.
247
248
- **Container-level OOM** (most common): `kubectl describe pod` shows
249
`Last State: Terminated`, `Reason: OOMKilled`, `Exit Code: 137`. The
250
container exceeded its cgroup memory limit. Differentiate an
251
**application memory leak/loop** (unbounded growth in logs and startup
252
command) from an **infrastructure capacity mismatch** (legitimate demand
253
exceeding `resources.limits.memory`).
254
- **Node-level (system) OOM**: the entire node ran out of memory; look for
255
evicted Pods and node-pressure eviction. The combined memory of all Pods
256
exceeded node capacity.
257
- **"Invisible" OOM** (`cgroup v1`): a child process is killed but the
258
main process (PID 1) keeps running, so Kubernetes never marks
259
`OOMKilled`. Search node logs in Cloud Logging:
260
261
```bash
262
gcloud logging read 'resource.type="k8s_node" AND resource.labels.cluster_name="{cluster_name}" AND jsonPayload.MESSAGE:("TaskOOM event" OR "ContainerDied")' --project="{project_id}"
263
```
264
265
A `TaskOOM` entry confirms an OOM kill; match its container ID to the
266
`ContainerDied` entry to find the affected Pod. On the node, `journalctl
267
-k` distinguishes container-level kills (`memory cgroup`, `memcg`) from
268
system-level kills (`Out of memory: Killed process`).
269
- Do not rely solely on sampled memory metrics — they often miss the spike
270
that triggers the kill. Then proceed to **Step 5** to propose fixes
271
(raise limits, fix the leak, or right-size the node pool).
272
- **Liveness Probe Failure (CrashLoop with no application error)**: if the
273
container restarts but its logs show no crash, the `kubelet` may be killing
274
it on failed liveness probes (default `failureThreshold: 3`). Confirm in
275
Cloud Logging:
276
277
```bash
278
gcloud logging read 'resource.type="k8s_node" AND log_id("kubelet") AND jsonPayload.MESSAGE:"failed liveness probe, will be restarted" AND resource.labels.cluster_name="{cluster_name}"' --project="{project_id}"
279
```
280
281
Common fixes: correct the probe type/path/port, raise `initialDelaySeconds`
282
or `timeoutSeconds`/`failureThreshold` for slow starts, or relieve CPU/disk
283
I/O contention causing probe timeouts. Keep probe commands lightweight.
284
- **Stack Trace / Unhandled Exception**: Look for language-specific stack
285
traces (e.g., `panic:`, `NullPointerException`, `Traceback (most recent
286
call)`). This indicates an application bug.
287
- **Egress Network Timeout**: Look for connection timeouts (e.g., `Connection
288
timed out`, `dial tcp: i/o timeout`). Proceed to **Step 4 (Verify
289
Connectivity)**.
290
- **Permission Errors (ReadOnlyRootFilesystem)**: Look for write errors (e.g.,
291
`Read-only file system`, `Permission denied` when writing to `/tmp` or
292
`/var/log`). Propose adding an `emptyDir` volume mount to that directory in
293
the manifest.
294
295
--------------------------------------------------------------------------------
296
297
### Step 4: Verify Service Connectivity and Network Policies
298
299
Troubleshoot connection drops to other services.
300
301
**Diagnostic Commands:**
302
303
```bash
304
# Verify target endpoint is active
305
kubectl get endpoints {target_service_name} -n {target_namespace}
306
307
# Query network policies inside namespace
308
kubectl get networkpolicies -n {workload_namespace} -o yaml
309
```
310
311
#### Logic & Dry-Run Fallback:
312
313
1. **Live Cluster Mode**:
314
315
- If `kubectl get endpoints` returns an empty list, the target
316
microservice itself is failing to schedule or boot (troubleshoot target
317
service).
318
- If endpoints exist but logs show timeouts, analyze `NetworkPolicy`
319
egress blocks to verify if egress traffic to the target service's
320
IP/port is allowed.
321
322
2. **Sandboxed / Dry-Run Mode**:
323
324
- If live `kubectl` queries fail or cluster connection is unavailable, do
325
NOT retry live cluster access or enter repetitive connection attempts.
326
- Immediately inspect the application source code (e.g. `worker.py`,
327
`app.go`, DB connection strings) or Deployment manifests to identify the
328
target service hostname (e.g. `account-db`) and destination port (e.g.
329
`5432`).
330
- Present the exact `kubectl get endpoints` and `kubectl get
331
networkpolicies` commands for the user, and synthesize the required
332
`NetworkPolicy` egress patch allowing traffic to the target service and
333
port.
334
335
--------------------------------------------------------------------------------
336
337
### Step 5: Propose GitOps Correction
338
339
Following the GitOps boundary, **do not apply changes directly** — this includes
340
both cluster manifest/config patches and any Google Cloud mutations (for example
341
`gcloud` IAM bindings or node-pool recreation). Present every change as a
342
reviewable suggestion: a manifest patch / PR, or a command for the user to run.
343
344
1. Synthesize the root cause analysis for the human operator (e.g.
345
*"payment-api is failing with exit code 137 because its memory limit is set
346
to 256Mi while actual usage spiked to 270Mi"*).
347
2. Generate the corrected YAML manifest patch (e.g. increase memory limits, add
348
missing Secret mounts, or add tolerations for Spot nodes).
349
3. Check if a branch or Pull Request (PR) already exists for this
350
workload/failure. If so, update the existing branch/PR or notify the user
351
instead of creating a duplicate. Otherwise, create a branch, commit the
352
change, open a Pull Request (PR) on GitHub, and conclude the workflow (do
353
not wait for human merge).
354
355
--------------------------------------------------------------------------------
356
357
## References
358
359
- [Troubleshoot OOM events](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/oom-events.md.txt)
360
- [Troubleshoot image pulls](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/image-pulls.md.txt)
361
- [Troubleshoot CrashLoopBackOff events](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/crashloopbackoff-events.md.txt)
362
- [Troubleshoot deployed workloads](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/deployed-workloads.md.txt)
363
- [Artifact Registry access control with GKE](https://docs.cloud.google.com/artifact-registry/docs/access-control.md.txt#gke)
364

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…