Skip to main content

Free Resource

The DevOps Troubleshooting Cheat Sheet

76 errors that eat an afternoon, across Kubernetes, Helm, Argo CD, Docker, GitHub Actions, Terraform, AWS, networking and TLS, Postgres, Prometheus, Git, and Linux. Each entry has the exact error text, what it actually means, the commands that find the real cause, and the usual fix. Every entry links to a full walkthrough.

Last updated: By Kiril Urbonas

The first 60 seconds of any incident

  1. What changed? A deploy, a config edit, a dependency bump, a feature flag, a cert renewal. Komodor's 2025 Enterprise Kubernetes Report attributes 79% of production incidents to a recent system change, so check the deploy log, git log and flag history first.
  2. Read the events and logs. kubectl describe / kubectl get events, docker logs, journalctl -u <service>. The error text is usually already there.
  3. Check resources. Memory, CPU, disk, inodes, file descriptors: kubectl top, free -h, df -h, df -i, ulimit -n.
  4. Check the network path. DNS first (dig, nslookup), then the port (ss -ltnp, curl -v), then policies and firewalls.
  5. Roll back if users are hurting. kubectl rollout undo, helm rollback, redeploy the last good image, revert the commit, turn the flag off. Restore service first, debug after.
  6. Write down the timeline as you go. Timestamps, commands run and what each showed. It makes the handoff, the postmortem and the next on-call shift much shorter.

Source for the 79% figure: Komodor 2025 Enterprise Kubernetes Report (vendor data from production environments, September 2025).

CrashLoopBackOff

Back-off restarting failed container

Cause: The container starts, exits, and kubelet restarts it with a growing delay. The restart count is a symptom; the exit code and the previous container's logs hold the cause.

kubectl describe pod <pod> -n <ns>
kubectl logs <pod> -n <ns> --previous
kubectl get pod <pod> -n <ns> -o jsonpath='{.status.containerStatuses[0].lastState.terminated}'

Fix: Read Last State: exit 1 is an app error (config, missing env var), 137 is OOM or a failed liveness probe, 127 is a wrong command.

Full diagnosis & fix: CrashLoopBackOff →

ImagePullBackOff / ErrImagePull

Failed to pull image ... not found / unauthorized / no such host

Cause: The node can't fetch the image: a wrong tag, a private registry without credentials, or a registry the node can't reach.

kubectl describe pod <pod> -n <ns> | grep -A10 Events
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.containers[*].image}'
kubectl get secret <pull-secret> -n <ns> -o jsonpath='{.data.\.dockerconfigjson}' | base64 -d

Fix: Match the event text: "not found" means fix the tag, "unauthorized" means add imagePullSecrets in the same namespace, "no such host" means check node DNS or egress.

Full diagnosis & fix: ImagePullBackOff / ErrImagePull →

OOMKilled (exit code 137)

Last State: Terminated, Reason: OOMKilled, Exit Code: 137

Cause: The container went over its memory limit and the kernel killed it. 137 means 128 + SIGKILL (9).

kubectl describe pod <pod> -n <ns> | grep -A5 'Last State'
kubectl top pod <pod> -n <ns> --containers
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.containers[*].resources}'

Fix: Check whether usage climbs steadily (a leak, fix the app) or spikes at load (raise the limit). For JVM and Node, cap the heap below the container limit.

Full diagnosis & fix: OOMKilled (exit code 137) →

Pod stuck in Pending

STATUS Pending, no node assigned

Cause: The scheduler can't place the pod, or a volume it needs isn't bound yet. The events always say which.

kubectl describe pod <pod> -n <ns> | grep -A10 Events
kubectl get nodes -o wide
kubectl get pvc -n <ns>

Fix: Insufficient cpu/memory means lower requests or add nodes. Taints or affinity mismatches mean fix the selector. Unbound PVC means fix the StorageClass.

Full diagnosis & fix: Pod stuck in Pending →

FailedScheduling

0/3 nodes are available: 3 Insufficient memory / had untolerated taint

Cause: Every node was ruled out. The message counts nodes per reason, so read each clause.

kubectl get events -n <ns> --field-selector reason=FailedScheduling
kubectl describe nodes | grep -A8 'Allocated resources'
kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints

Fix: Requests are scheduled, not actual usage. Right-size requests, add a toleration, or let the cluster autoscaler add capacity.

Full diagnosis & fix: FailedScheduling →

PersistentVolumeClaim Pending

waiting for first consumer / no persistent volumes available for this claim

Cause: No StorageClass, no default StorageClass, a CSI driver that isn't running, or WaitForFirstConsumer waiting on a pod.

kubectl describe pvc <pvc> -n <ns>
kubectl get storageclass
kubectl get pods -n kube-system | grep -i csi

Fix: Set storageClassName to a class that exists (or mark one as default) and confirm the CSI controller pods are healthy.

Full diagnosis & fix: PersistentVolumeClaim Pending →

Pod Evicted

The node was low on resource: memory / ephemeral-storage

Cause: The kubelet evicted pods to protect the node under memory or disk pressure. BestEffort pods go first.

kubectl get pods -A --field-selector status.phase=Failed
kubectl describe node <node> | grep -A6 Conditions
kubectl delete pods -A --field-selector status.phase=Failed

Fix: Set requests and limits (including ephemeral-storage), stop writing logs or temp files to the container filesystem, and clean up evicted pods.

Full diagnosis & fix: Pod Evicted →

Node NotReady

STATUS NotReady, Kubelet stopped posting node status

Cause: The kubelet stopped reporting: kubelet or container runtime down, the CNI broken, disk or memory pressure, or the node lost its network.

kubectl describe node <node> | grep -A10 Conditions
journalctl -u kubelet -n 100 --no-pager
systemctl status containerd

Fix: Fix what the kubelet log names (certificate expiry, runtime socket, CNI not initialized, full disk). On managed clusters, replacing the node is often fastest.

Full diagnosis & fix: Node NotReady →

CreateContainerConfigError

Error: configmap "x" not found / couldn't find key y in Secret

Cause: The kubelet can't build the container config. Almost always a ConfigMap, Secret, or key reference that doesn't exist in that namespace.

kubectl describe pod <pod> -n <ns> | grep -i error
kubectl get configmap,secret -n <ns>
kubectl get secret <name> -n <ns> -o jsonpath='{.data}'

Fix: Create the missing object or key in the pod's namespace, or mark the reference optional: true if the app can start without it.

Full diagnosis & fix: CreateContainerConfigError →

Service not reachable

connection refused / timed out calling a ClusterIP Service

Cause: The selector matches no pods, the targetPort is wrong, the pods aren't Ready, or a NetworkPolicy blocks traffic.

kubectl get endpointslices -n <ns> -l kubernetes.io/service-name=<svc>
kubectl get svc <svc> -n <ns> -o yaml | grep -A5 -E 'selector|ports'
kubectl run tmp --rm -it --image=busybox -- wget -qO- http://<svc>.<ns>:<port>

Fix: Empty endpoints means the selector labels don't match the pods. Endpoints exist but nothing answers means targetPort doesn't match containerPort.

Full diagnosis & fix: Service not reachable →

Ingress 502 Bad Gateway / 504 Gateway Timeout

502 Bad Gateway or 504 Gateway Timeout from the ingress controller

Cause: 502: the controller reached no healthy backend (wrong port, pods not Ready, upstream reset). 504: the backend answered too slowly.

kubectl describe ingress <ing> -n <ns>
kubectl logs -n ingress-nginx deploy/ingress-nginx-controller --tail=100
kubectl get endpointslices -n <ns> -l kubernetes.io/service-name=<svc>

Fix: For 502, fix the Service port and readiness. For 504, raise proxy-read-timeout via annotation only after confirming the backend is slow, not stuck.

Full diagnosis & fix: Ingress 502 Bad Gateway / 504 Gateway Timeout →

DNS resolution fails in pods

could not resolve host / i/o timeout on lookup

Cause: CoreDNS pods are down or overloaded, a NetworkPolicy blocks port 53, or ndots:5 makes external lookups slow.

kubectl run dnstest --rm -it --image=busybox:1.36 -- nslookup kubernetes.default
kubectl get pods -n kube-system -l k8s-app=kube-dns
kubectl logs -n kube-system -l k8s-app=kube-dns --tail=50

Fix: Restore CoreDNS, allow UDP and TCP 53 egress, and use fully qualified names (trailing dot) or a lower ndots for external hosts.

Full diagnosis & fix: DNS resolution fails in pods →

Too many open files (Kubernetes)

too many open files / failed to create fsnotify watcher

Cause: The node's inotify limits or the container's file descriptor limit ran out, often from log tailers or file watchers.

sysctl fs.inotify.max_user_instances fs.inotify.max_user_watches
kubectl exec <pod> -- sh -c 'ulimit -n'
kubectl exec <pod> -- sh -c 'ls /proc/1/fd | wc -l'

Fix: Raise fs.inotify.max_user_instances and max_user_watches on nodes (DaemonSet or node config), and fix descriptor leaks in the app.

Full diagnosis & fix: Too many open files (Kubernetes) →

Kubernetes exit codes reference

Exit Code: 1 / 126 / 127 / 137 / 139 / 143

Cause: The exit code is the fastest clue to why a container stopped. Codes above 128 mean a signal: subtract 128 to get it.

kubectl get pod <pod> -n <ns> -o jsonpath='{.status.containerStatuses[*].lastState.terminated.exitCode}'
kubectl describe pod <pod> -n <ns> | grep -E 'Exit Code|Reason'

Fix: Use the exit code table below to go from the number to the likely cause.

Full diagnosis & fix: Kubernetes exit codes reference →

HPA not scaling (<unknown> targets)

TARGETS <unknown>/80% / FailedGetResourceMetric: unable to get metrics for resource cpu

Cause: The HPA can't read metrics. Either metrics-server is missing or unhealthy, or the target pods have no CPU/memory requests, so utilization (usage divided by request) can't be computed.

kubectl get hpa -n <ns>
kubectl describe hpa <hpa> -n <ns>
kubectl get apiservice v1beta1.metrics.k8s.io
kubectl top pods -n <ns>

Fix: Install or repair metrics-server and set resources.requests on every container in the target pods, sidecars included. If it scales up but never down, that is the 300-second scale-down stabilization window working as designed.

Full diagnosis & fix: HPA not scaling (<unknown> targets) →

RBAC Forbidden

Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:<ns>:<sa>" cannot list resource "pods" in API group "" in the namespace "<ns>"

Cause: No Role or ClusterRole bound to that identity grants that verb on that resource. The message names the user, verb, resource, API group and namespace, so it is the exact spec for the fix.

kubectl auth can-i list pods -n <ns> --as=system:serviceaccount:<ns>:<sa>
kubectl auth can-i --list -n <ns> --as=system:serviceaccount:<ns>:<sa>
kubectl get rolebindings,clusterrolebindings -A -o wide | grep <sa>

Fix: Create a Role with exactly that verb, resource and API group, and bind it to the identity in that namespace. Binding cluster-admin makes the error go away and creates a much bigger problem.

Full diagnosis & fix: RBAC Forbidden →

Readiness / liveness probe failed

Readiness probe failed: HTTP probe failed with statuscode: 503 / Liveness probe failed: Get "http://10.0.1.7:8080/healthz": context deadline exceeded

Cause: A failing readiness probe removes the pod from Service endpoints (READY 0/1, no restarts). A failing liveness probe restarts the container, which often looks like CrashLoopBackOff with exit 137 or 143. Usual roots: wrong path or port, the 1-second default timeoutSeconds on a slow endpoint, or a health check that calls the database.

kubectl describe pod <pod> -n <ns> | grep -iA3 probe
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.containers[0].livenessProbe}'
kubectl port-forward pod/<pod> 8080:<port> & curl -sv localhost:8080/healthz
kubectl get endpointslices -n <ns> -l kubernetes.io/service-name=<svc>

Fix: Point liveness at a cheap endpoint that never checks downstream dependencies, raise timeoutSeconds, and give slow-booting apps a startupProbe instead of a long initialDelaySeconds.

Full diagnosis & fix: Readiness / liveness probe failed →

Rollout stuck (ProgressDeadlineExceeded)

Waiting for deployment "<name>" rollout to finish: 1 out of 3 new replicas have been updated... / error: deployment "<name>" exceeded its progress deadline

Cause: The new pods never become Ready, so the Deployment stops progressing after progressDeadlineSeconds (600 by default). The old ReplicaSet keeps serving, so this is a readiness, image or capacity problem in the new pods.

kubectl rollout status deploy/<name> -n <ns>
kubectl describe deploy <name> -n <ns> | grep -A6 Conditions
kubectl get rs -n <ns> -l app=<label>
kubectl rollout undo deploy/<name> -n <ns>

Fix: Debug the newest ReplicaSet's pods like any failing pod (describe, logs --previous). If users are affected, run rollout undo first and fix forward after.

Full diagnosis & fix: Rollout stuck (ProgressDeadlineExceeded) →

Helm: another operation is in progress

Error: UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress

Cause: An earlier Helm run was interrupted (a cancelled CI job, a runner killed at its timeout) and left the release in pending-install, pending-upgrade or pending-rollback. Helm treats that as a lock.

helm status <release> -n <ns>
helm history <release> -n <ns>
helm rollback <release> <last-deployed-revision> -n <ns>
kubectl get secrets -n <ns> -l owner=helm,name=<release>

Fix: Confirm no Helm job is still running, then roll back to the last revision whose status is deployed. Deleting the pending release secret is the last resort. Prevent it with a CI concurrency group and a Helm --timeout shorter than the job timeout.

Full diagnosis & fix: Helm: another operation is in progress →

Helm: has no deployed releases

Error: UPGRADE FAILED: "<release>" has no deployed releases

Cause: No revision of the release is in the deployed state, usually because the very first install failed. There is nothing healthy for the upgrade to build on.

helm history <release> -n <ns>
helm uninstall <release> -n <ns>
helm upgrade --install <release> <chart> -n <ns> --rollback-on-failure --timeout 10m  # Helm 3: --atomic

Fix: If the release never deployed, nothing useful is running: uninstall it and install again with --rollback-on-failure (--atomic on Helm 3) so a failed install cleans up after itself instead of leaving a broken release.

Full diagnosis & fix: Helm: has no deployed releases →

Argo CD app stays OutOfSync

Sync Status: OutOfSync (comes back right after every successful sync)

Cause: Something changes the live object after Argo CD applies it: a mutating webhook, an HPA that owns replicas, a controller that fills in defaults, or a Helm template that renders differently each time (random passwords, timestamps).

argocd app diff <app>
argocd app get <app> --refresh
kubectl get <kind> <name> -n <ns> -o yaml --show-managed-fields

Fix: Find the drifting field in the diff. Remove it from Git when another controller owns it (replicas under an HPA), or add ignoreDifferences for that path with RespectIgnoreDifferences=true in syncOptions.

Full diagnosis & fix: Argo CD app stays OutOfSync →

Argo CD ComparisonError / manifest generation error

ComparisonError: rpc error: code = Unknown desc = Manifest generation error (cached): ... authentication required / helm dependency build failed

Cause: The repo-server can't render the app: Git or Helm repo credentials expired, a chart dependency is missing, the path or revision doesn't exist, or a config management plugin timed out. "(cached)" means Argo CD is reusing the last error, not retrying.

argocd app get <app> --hard-refresh
argocd repo list
kubectl logs -n argocd deploy/argocd-repo-server --tail=100
helm template <chart-path> -f values.yaml  # reproduce the render locally

Fix: Reproduce the render locally with the same path and revision, fix credentials with argocd repo add, then hard refresh to clear the cached error.

Full diagnosis & fix: Argo CD ComparisonError / manifest generation error →

Cannot connect to the Docker daemon

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Cause: Usually a stopped service, a stale docker context, or a DOCKER_HOST variable pointing somewhere else. Rarely a broken install.

sudo systemctl status docker
docker context ls
echo $DOCKER_HOST

Fix: Start the service (sudo systemctl enable --now docker), switch to the right context, or unset DOCKER_HOST. On macOS, start Docker Desktop.

Full diagnosis & fix: Cannot connect to the Docker daemon →

Permission denied on docker.sock

permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Cause: Your user isn't in the docker group, or the group change hasn't reached your current shell.

ls -l /var/run/docker.sock
id -nG
sudo usermod -aG docker $USER && newgrp docker

Fix: Add the user to the docker group and start a new login session. Don't chmod 666 the socket: docker group membership is root-equivalent anyway, and 666 gives it to everyone.

Full diagnosis & fix: Permission denied on docker.sock →

Port is already allocated

Bind for 0.0.0.0:8080 failed: port is already allocated

Cause: Another container or a host process already holds that host port.

docker ps --filter publish=8080
sudo ss -ltnp 'sport = :8080'
sudo lsof -i :8080

Fix: Stop the old container (often a leftover from a previous compose up) or map a different host port: -p 8081:8080.

Full diagnosis & fix: Port is already allocated →

No space left on device

no space left on device (during build, pull, or write)

Cause: Images, stopped containers, build cache, and volumes have filled the disk under /var/lib/docker.

docker system df
df -h /var/lib/docker
docker builder prune -f && docker image prune -a -f

Fix: Prune build cache and unused images first. Run docker system prune --volumes only when you're sure no volume holds data you need.

Full diagnosis & fix: No space left on device →

exec format error

exec /usr/local/bin/app: exec format error

Cause: The image was built for a different CPU architecture (arm64 on an Apple Silicon Mac, run on an amd64 server), or the entrypoint script has no shebang.

docker image inspect <image> --format '{{.Architecture}}'
uname -m
docker buildx build --platform linux/amd64,linux/arm64 -t <image> --push .

Fix: Build for the target platform (or multi-arch with buildx) and make sure shell entrypoints start with #!/bin/sh.

Full diagnosis & fix: exec format error →

Container exits immediately

docker ps shows nothing; docker ps -a shows Exited (0) or Exited (1)

Cause: PID 1 finished. A container lives only as long as its main process: a backgrounded daemon or a finished script ends it.

docker ps -a --filter name=<name>
docker logs <container>
docker inspect <container> --format '{{.State.ExitCode}} {{.Config.Cmd}}'

Fix: Run the main process in the foreground (nginx -g 'daemon off;'), and fix whatever error the logs show for non-zero exits.

Full diagnosis & fix: Container exits immediately →

Docker exit code 137

Exited (137)

Cause: The container got SIGKILL: either the OOM killer (memory limit hit) or docker stop timing out and killing it.

docker inspect <container> --format '{{.State.OOMKilled}}'
docker stats --no-stream
dmesg -T | grep -i -E 'killed process|oom'

Fix: If OOMKilled is true, raise --memory or reduce usage. If false, the app ignores SIGTERM: handle the signal or use exec form for CMD.

Full diagnosis & fix: Docker exit code 137 →

Docker build cache not used

every build reruns npm install / pip install from scratch

Cause: A layer early in the Dockerfile changes on every build (usually COPY . . before dependency install), so every later layer is invalidated.

docker build --progress=plain . 2>&1 | grep -E 'CACHED|RUN'
docker history <image>

Fix: Copy the lockfile first, install dependencies, then copy the source. Add a .dockerignore and use cache mounts (RUN --mount=type=cache).

Full diagnosis & fix: Docker build cache not used →

Docker Compose errors

service depends on undefined service / network not found / yaml: line N

Cause: Most Compose failures are the same handful: YAML indentation, depends_on without healthchecks, stale networks, missing .env values.

docker compose config
docker compose ps -a
docker compose logs --tail=50 <service>

Fix: Run docker compose config first: it validates the file and shows the fully interpolated result, which catches most errors in seconds.

Full diagnosis & fix: Docker Compose errors →

no matching manifest for linux/arm64

no matching manifest for linux/arm64/v8 in the manifest list entries / WARNING: The requested image's platform (linux/amd64) does not match the detected host platform

Cause: The image was published for one CPU architecture only. It shows up on Apple Silicon laptops and Graviton or other ARM nodes.

docker buildx imagetools inspect <image>
docker run --platform linux/amd64 <image>
docker buildx build --platform linux/amd64,linux/arm64 -t <image> --push .

Fix: Publish a multi-arch image with buildx. Running amd64 under emulation works on a laptop but is slow, and a mismatched binary in production shows up as exec format error.

Full diagnosis & fix: no matching manifest for linux/arm64 →

COPY failed: not found

failed to solve: failed to compute cache key: failed to calculate checksum of ref ...: "/app/dist": not found

Cause: COPY paths are relative to the build context, not to the Dockerfile, and anything in .dockerignore is never sent to the builder. In multi-stage builds, COPY --from needs the path to exist in that stage.

docker build -f path/to/Dockerfile <context-dir>
cat .dockerignore
docker build --progress=plain --no-cache .

Fix: Build from the directory that contains the files, check .dockerignore for a pattern that excludes them, and for COPY --from confirm the earlier stage really wrote that path.

Full diagnosis & fix: COPY failed: not found →

GitHub Actions errors

GitHub Actions recipes →

Resource not accessible by integration

HttpError: Resource not accessible by integration (403)

Cause: The workflow's GITHUB_TOKEN lacks the permission the step needs. Repositories and organizations created since February 2023 default to a read-only token, and pull requests from forks always get a read-only token.

gh api repos/<owner>/<repo>/actions/permissions/workflow
permissions:            # at job level, narrowest scope
  contents: read
  pull-requests: write

Fix: Grant only the scope the step needs (pull-requests: write, issues: write, packages: write) on the job that needs it. For fork PRs, don't switch to pull_request_target and check out the PR code: that is the classic "pwn request".

Full diagnosis & fix: Resource not accessible by integration →

OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity

Error: Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity

Cause: The IAM role's trust policy doesn't match the token's claims: a sub that names the wrong branch, environment or event, an aud other than sts.amazonaws.com, or a job without permissions: id-token: write.

aws iam get-role --role-name <role> --query Role.AssumeRolePolicyDocument
aws iam list-open-id-connect-providers
permissions:
  id-token: write

Fix: Make the token.actions.githubusercontent.com:sub condition match how the job really runs. A job with environment: prod gets repo:<owner>/<repo>:environment:prod as its subject, not the branch ref.

Full diagnosis & fix: OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity →

Cache never hits

Cache not found for input keys: Linux-npm-...

Cause: The key changes every run, the cache lives on a branch this run can't read (a run sees its own branch's caches and the default branch's), or it was evicted by the repository's cache size limit or after 7 days unused.

gh cache list --sort last_accessed_at
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: ${{ runner.os }}-npm-

Fix: Key on the lock file hash, add restore-keys for partial hits, and let a run on the default branch seed the cache so feature branches inherit it. The setup-node and setup-python cache input does most of this for you.

Full diagnosis & fix: Cache never hits →

Secret is empty in the workflow

Error: Input required and not supplied: token / the secret prints as an empty string

Cause: Secrets are not passed to workflows triggered by fork pull requests, Dependabot runs only see Dependabot secrets, environment secrets need environment: on the job, and reusable workflows only get what the caller passes.

gh secret list
gh secret list --env <environment>
gh secret list --app dependabot
secrets: inherit   # on the job that calls a reusable workflow

Fix: Find which of the four cases applies. Add the secret to the right store (repo, environment, Dependabot) or pass it to the reusable workflow explicitly. Never echo a secret to debug it.

Full diagnosis & fix: Secret is empty in the workflow →

Runner out of disk space

System.IO.IOException: No space left on device / You are running out of disk space

Cause: GitHub documents 14 GB of SSD on standard hosted Linux runners, and preinstalled SDKs, Docker layers and build caches fill it fast.

df -h && docker system df
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
docker builder prune -af

Fix: Delete preinstalled SDKs you don't use at the start of the job, prune between image builds, use the BuildKit gha cache instead of local layers, or move the job to a larger runner.

Full diagnosis & fix: Runner out of disk space →

Error acquiring the state lock

Error acquiring the state lock: ConditionalCheckFailedException / Lock Info: ID ...

Cause: Another run holds the lock, or a crashed run (killed CI job, closed laptop) left a stale one.

terraform plan  # copy the Lock Info ID from the error
terraform force-unlock <LOCK_ID>

Fix: First confirm nobody else is running Terraform (check CI and teammates), then force-unlock with the exact ID. Never unlock a lock that's in active use.

Full diagnosis & fix: Error acquiring the state lock →

Error: Cycle

Error: Cycle: aws_security_group.a, aws_security_group.b

Cause: Two or more resources depend on each other, so Terraform can't order them.

terraform graph -type=plan | dot -Tsvg > graph.svg
terraform validate

Fix: Break the loop with a separate resource (for example aws_security_group_rule instead of inline rules) or remove an unneeded depends_on.

Full diagnosis & fix: Error: Cycle →

Drift from real infrastructure

plan shows changes nobody made in code

Cause: Someone changed resources outside Terraform (console clicks, scripts, another tool).

terraform plan -refresh-only
terraform apply -refresh-only
terraform plan -detailed-exitcode  # exit 2 = drift, useful in CI

Fix: Decide which side is right: accept the real state into code, or apply to put infra back. Run a scheduled drift check in CI.

Full diagnosis & fix: Drift from real infrastructure →

Provider version conflicts / lock file

Inconsistent dependency lock file / no available releases match the given constraints

Cause: Version constraints across modules can't all be met, or .terraform.lock.hcl pins a version the constraints no longer allow.

terraform providers
terraform init -upgrade
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64

Fix: Loosen or align constraints across modules, run init -upgrade, and commit the lock file with hashes for every platform your team and CI use.

Full diagnosis & fix: Provider version conflicts / lock file →

Resource already exists

Error creating ...: EntityAlreadyExists / BucketAlreadyOwnedByYou

Cause: The resource exists in the cloud but not in Terraform state, so Terraform tries to create it again.

terraform import aws_s3_bucket.logs my-logs-bucket
terraform plan -generate-config-out=generated.tf  # with an import block

Fix: Import it into state (import blocks on Terraform 1.5+), then plan until it shows no changes.

Full diagnosis & fix: Resource already exists →

Plan wants to replace a resource

# aws_db_instance.main must be replaced / -/+ destroy and then create replacement / # forces replacement

Cause: You changed an argument the provider can't update in place (engine, identifier, availability_zone, subnet group), renamed a resource address, or changed a count index or for_each key.

terraform plan -out=tfplan && terraform show -no-color tfplan | grep -B3 'forces replacement'
terraform state list | grep <name>
moved { from = aws_db_instance.old  to = aws_db_instance.main }

Fix: Read which attribute forces replacement. Use moved blocks for renames, lifecycle { prevent_destroy = true } on stateful resources, and ignore_changes for attributes managed outside Terraform. Never auto-apply a plan that replaces a database.

Full diagnosis & fix: Plan wants to replace a resource →

Invalid for_each argument

Error: Invalid for_each argument: The "for_each" map includes keys derived from resource attributes that cannot be determined until apply

Cause: for_each keys must be known at plan time. Keys built from IDs or attributes of resources that don't exist yet are unknown until apply.

terraform console
terraform plan -target=<resource>   # one-off workaround

Fix: Key the map on values you control, such as names from variables, and keep the unknown values in the map values, not the keys. -target works once but leaves you with a two-step apply forever.

Full diagnosis & fix: Invalid for_each argument →

AccessDenied: is not authorized to perform

An error occurred (AccessDenied) when calling the GetObject operation: User: arn:aws:sts::<acct>:assumed-role/<role>/<session> is not authorized to perform: s3:GetObject on resource: <arn> because no identity-based policy allows the s3:GetObject action

Cause: Either no policy allows the action, or something denies it: a service control policy, a permissions boundary, a resource policy or a session policy. The end of the message says which kind of policy blocked you.

aws sts get-caller-identity
aws iam simulate-principal-policy --policy-source-arn <role-arn> --action-names s3:GetObject --resource-arns <arn>
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=GetObject --max-results 5

Fix: Check who you are first: the wrong profile or role is the most common cause. "no identity-based policy allows" means add a permission to the role. "explicit deny in a service control policy" or "permissions boundary" means the fix lives outside your role, with whoever owns that policy.

Full diagnosis & fix: AccessDenied: is not authorized to perform →

ExpiredToken / InvalidClientTokenId

An error occurred (ExpiredToken): The security token included in the request is expired / (InvalidClientTokenId) / Unable to locate credentials

Cause: Short-lived credentials (SSO, an assumed role, OIDC) expired, the access key was deleted, or the CLI picked up stale keys from environment variables, which override your profile.

aws sts get-caller-identity
env | grep ^AWS_
aws configure list
aws sso login --profile <profile>

Fix: Unset stale AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN, log in again, and raise the role's MaxSessionDuration if long jobs keep outliving their credentials.

Full diagnosis & fix: ExpiredToken / InvalidClientTokenId →

S3 403 Forbidden on an object

An error occurred (403) when calling the HeadObject operation: Forbidden

Cause: S3 combines the IAM policy, the bucket policy, Block Public Access, object ownership and the KMS key policy. A 403 can also mean the key doesn't exist: without s3:ListBucket, S3 returns 403 instead of 404.

aws s3api head-object --bucket <bucket> --key <key>
aws s3api get-bucket-policy --bucket <bucket>
aws s3api get-public-access-block --bucket <bucket>
aws s3api get-bucket-encryption --bucket <bucket>

Fix: Confirm the key exists and that you have s3:ListBucket on the bucket ARN (arn:aws:s3:::bucket, not bucket/*). For SSE-KMS objects the caller also needs kms:Decrypt on the key.

Full diagnosis & fix: S3 403 Forbidden on an object →

Unexpected AWS bill spike

AWS Budgets: actual cost exceeded your threshold / Cost Anomaly Detection alert

Cause: Usually one of: NAT gateway data processing, a runaway Auto Scaling group or recursive Lambda, cross-AZ or internet data transfer, forgotten GPU instances, or leaked keys mining crypto in a region you never use.

aws ce get-cost-and-usage --time-period Start=<yyyy-mm-dd>,End=<yyyy-mm-dd> --granularity DAILY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[].Instances[].[InstanceId,InstanceType,LaunchTime]' --output table
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=RunInstances --max-results 20

Fix: Group the last three days by service, then by usage type. Cost data lags by up to a day, so check CloudTrail for what launched. Instances or regions you don't recognize make it a security incident: rotate keys first, then clean up.

Full diagnosis & fix: Unexpected AWS bill spike →

x509: certificate has expired

x509: certificate has expired or is not yet valid / SSL certificate problem: certificate has expired

Cause: The leaf or an intermediate certificate is past its notAfter date, or the client's clock is wrong. In clusters, a cert-manager renewal may have failed quietly, or kubeadm's control-plane certificates hit their one-year expiry.

echo | openssl s_client -connect <host>:443 -servername <host> 2>/dev/null | openssl x509 -noout -dates -subject -issuer
kubectl get certificate -A
kubeadm certs check-expiration
timedatectl

Fix: Renew, then reload the server (many only read certs at startup), and check the whole chain, not just the leaf. Alert 21+ days before expiry. Public certificate lifetimes drop to 200 days from March 2026 and 47 days by 2029, so renewal has to be automated.

Full diagnosis & fix: x509: certificate has expired →

x509: certificate signed by unknown authority

x509: certificate signed by unknown authority / SSL certificate problem: unable to get local issuer certificate

Cause: The client doesn't trust the issuer: a private or internal CA, a corporate TLS-inspecting proxy, a server that sends its leaf without the intermediate, or a slim container image with no CA bundle at all.

openssl s_client -connect <host>:443 -servername <host> -showcerts </dev/null
ls -l /etc/ssl/certs/ca-certificates.crt
apk add ca-certificates   # Alpine; apt-get install ca-certificates on Debian/Ubuntu
update-ca-certificates

Fix: If -showcerts prints a single certificate, fix the server to send the full chain. Otherwise add the CA to the trust store (or point SSL_CERT_FILE / NODE_EXTRA_CA_CERTS at it). Don't ship curl -k or InsecureSkipVerify.

Full diagnosis & fix: x509: certificate signed by unknown authority →

502 Bad Gateway (Nginx upstream)

502 Bad Gateway / connect() failed (111: Connection refused) while connecting to upstream / upstream prematurely closed connection while reading response header

Cause: The proxy reached for the upstream and got nothing usable. The app is down, it listens on a different port or interface (127.0.0.1 vs 0.0.0.0), it crashed mid-request, or its keep-alive timeout is shorter than the proxy's, so the proxy reuses a connection the app already closed.

tail -n 50 /var/log/nginx/error.log
ss -ltnp | grep <port>
curl -sv http://127.0.0.1:<port>/health
nginx -T | grep -n proxy_pass

Fix: The error.log line names the cause: "111: Connection refused" means nothing is listening; "prematurely closed" means the app died or hung up. Set the app's keep-alive timeout longer than the proxy's or load balancer's idle timeout.

Full diagnosis & fix: 502 Bad Gateway (Nginx upstream) →

504 Gateway Timeout

504 Gateway Time-out / upstream timed out (110: Connection timed out) while reading response header from upstream

Cause: The upstream accepted the connection but didn't answer in time: proxy_read_timeout is 60 seconds by default in Nginx, and the AWS ALB idle timeout is also 60 seconds. Slow queries, exhausted worker pools and a slow dependency are the usual roots.

grep 'upstream timed out' /var/log/nginx/error.log | tail
curl -o /dev/null -s -w 'connect=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' http://127.0.0.1:<port>/<path>
kubectl top pods -n <ns>

Fix: Find the slow endpoint before you touch timeouts. A bigger proxy_read_timeout hides the problem and holds connections open; move long work to a background job and return 202 Accepted.

Full diagnosis & fix: 504 Gateway Timeout →

Connection refused vs connection timed out

connect: connection refused / dial tcp 10.0.3.14:5432: i/o timeout / Connection timed out

Cause: Refused is a fast answer: the host is reachable but nothing listens on that port (or a firewall actively rejects). Timed out means packets vanish: a security group, NACL, NetworkPolicy or host firewall drops them, a route is wrong, or the host is down.

nc -vz -w 3 <host> <port>
ss -ltnp | grep <port>
sudo tcpdump -ni any host <ip> and port <port>
traceroute -T -p <port> <host>

Fix: Refused: fix the listener (process down, wrong port, bound to 127.0.0.1). Timed out: walk the path outward from the source, checking security groups, NACLs, NetworkPolicy and the host firewall in that order.

Full diagnosis & fix: Connection refused vs connection timed out →

SSH Permission denied (publickey)

user@host: Permission denied (publickey).

Cause: The server accepted none of the keys the client offered: wrong username, wrong key, key missing from authorized_keys, or ~/.ssh permissions so loose that sshd ignores the file.

ssh -vvv user@host
ssh-add -l
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys   # on the server
sudo journalctl -u ssh -n 50   # sshd on RHEL-family

Fix: The -vvv output lists which keys were offered and which were refused. Check the username (ubuntu, ec2-user, admin), then the server log, which states the real reason, such as bad ownership on the home directory.

Full diagnosis & fix: SSH Permission denied (publickey) →

Postgres & Prometheus errors

Postgres query plans and indexes →

Postgres: too many clients already

FATAL: sorry, too many clients already / FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute

Cause: Every app instance opens its own pool, so replicas × pool size × worker processes goes past max_connections (100 by default). Autoscaling and serverless functions multiply it fast, and idle-in-transaction sessions hold slots doing nothing.

psql -c 'SHOW max_connections;'
psql -c 'SELECT state, count(*) FROM pg_stat_activity GROUP BY state;'
psql -c "SELECT pid, now() - state_change AS idle_for, left(query, 60) FROM pg_stat_activity WHERE state = 'idle in transaction' ORDER BY idle_for DESC;"

Fix: Put PgBouncer in transaction mode in front of the database, size each app pool so the total fits, and set idle_in_transaction_session_timeout. Raising max_connections costs memory per connection and usually just moves the cliff.

Full diagnosis & fix: Postgres: too many clients already →

Postgres query suddenly slow

ERROR: canceling statement due to statement timeout / a query that took milliseconds now takes seconds

Cause: The plan changed (stale statistics, a missing or unused index, data growth past a threshold) or the query waits on a lock.

SELECT query, calls, mean_exec_time, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
EXPLAIN (ANALYZE, BUFFERS) <query>;
SELECT pid, wait_event_type, wait_event, left(query, 60) FROM pg_stat_activity WHERE wait_event IS NOT NULL;
ANALYZE <table>;

Fix: Rank by total time, not the single slowest call. In EXPLAIN ANALYZE, a big gap between estimated and actual rows means stale statistics (run ANALYZE); a Seq Scan over a large filtered table means a missing index.

Full diagnosis & fix: Postgres query suddenly slow →

Postgres replication lag

Reads from the replica return stale data / replay_lag keeps growing

Cause: The replica can't replay WAL as fast as the primary writes it: a long query on the replica pauses replay (max_standby_streaming_delay), slow disk or network, or a bulk write on the primary.

SELECT client_addr, state, write_lag, flush_lag, replay_lag FROM pg_stat_replication;  -- on the primary
SELECT now() - pg_last_xact_replay_timestamp() AS lag;  -- on the replica
SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained FROM pg_replication_slots;

Fix: Find whether the lag is in write, flush or replay. Replay lag alongside a long replica query is a standby conflict setting. An inactive replication slot retains WAL until the primary's disk fills, so drop slots nothing uses.

Full diagnosis & fix: Postgres replication lag →

Prometheus high cardinality / OOM

Prometheus OOMKilled, queries time out, prometheus_tsdb_head_series keeps climbing

Cause: A label with unbounded values (user_id, raw URL path, pod name in a churning cluster) creates a new series for every value, and Prometheus memory scales with active series.

topk(10, count by (__name__)({__name__=~".+"}))
curl -s localhost:9090/api/v1/status/tsdb | jq '.data.seriesCountByMetricName[:10]'
promtool tsdb analyze /prometheus

Fix: Find the top metrics and labels, then drop or bucket the label in the code that emits it. metric_relabel_configs with action: labeldrop is the stopgap. Set sample_limit per scrape job so one bad deploy can't take Prometheus down.

Full diagnosis & fix: Prometheus high cardinality / OOM →

Merge conflict

CONFLICT (content): Merge conflict in <file>. Automatic merge failed

Cause: Both branches changed the same lines. Git can't pick a winner, so it asks you.

git status
git diff --name-only --diff-filter=U
git merge --abort  # or git rebase --abort, to start over

Fix: Edit each file between the <<<<<<< and >>>>>>> markers, git add it, then git commit (or git rebase --continue).

Full diagnosis & fix: Merge conflict →

Push rejected (non-fast-forward)

! [rejected] main -> main (fetch first) / Updates were rejected because the tip of your current branch is behind

Cause: The remote has commits you don't have locally.

git fetch origin
git log --oneline HEAD..origin/main
git pull --rebase origin main && git push

Fix: Integrate the remote work first. If you must overwrite, use git push --force-with-lease, never plain --force on shared branches.

Full diagnosis & fix: Push rejected (non-fast-forward) →

Detached HEAD

You are in 'detached HEAD' state

Cause: You checked out a commit or tag instead of a branch. New commits aren't on any branch yet.

git status
git switch -c <new-branch>  # keep the work
git reflog  # find commits that look lost

Fix: Create a branch where you are to keep the commits, or git switch main to leave. Lost commits are in the reflog for weeks.

Full diagnosis & fix: Detached HEAD →

Not a git repository

fatal: not a git repository (or any of the parent directories): .git

Cause: You're outside the repo, the .git directory is missing, or (in CI and containers) the checkout is owned by another user.

git rev-parse --show-toplevel
ls -la .git
git config --global --add safe.directory "$PWD"

Fix: cd into the repo root. In CI, check the checkout step ran. For the "dubious ownership" variant, add the path to safe.directory.

Full diagnosis & fix: Not a git repository →

Authentication failed (password auth removed)

remote: Support for password authentication was removed on August 13, 2021. / fatal: Authentication failed for 'https://github.com/<owner>/<repo>.git/'

Cause: GitHub stopped accepting account passwords for Git over HTTPS. You need a personal access token, a credential helper, or SSH. A stale cached credential produces the same error.

git remote -v
gh auth login && gh auth setup-git
git remote set-url origin git@github.com:<owner>/<repo>.git
ssh -T git@github.com

Fix: Use gh auth setup-git (or Git Credential Manager) for HTTPS, or switch the remote to SSH. If it worked yesterday, clear the stale entry from your OS keychain.

Full diagnosis & fix: Authentication failed (password auth removed) →

Refusing to merge unrelated histories

fatal: refusing to merge unrelated histories

Cause: The two branches share no common commit, usually because the repo was created on GitHub with a README while a separate local repo was initialized.

git log --oneline --graph --all | head -30
git pull origin main --allow-unrelated-histories

Fix: Allow it only when you know both histories belong together. If they shouldn't, you've pointed at the wrong remote.

Full diagnosis & fix: Refusing to merge unrelated histories →

Out of memory (OOM killer)

Out of memory: Killed process 1234 (java) total-vm:... anon-rss:...

Cause: The kernel ran out of memory and killed the process with the highest oom_score to keep the box alive.

dmesg -T | grep -i -E 'out of memory|killed process'
journalctl -k --since '1 hour ago' | grep -i oom
free -h && ps aux --sort=-rss | head

Fix: Read anon-rss in the kill line to see what used the memory. Fix the leak or cap the service (systemd MemoryMax), and watch PSI to see pressure before the kill.

Full diagnosis & fix: Out of memory (OOM killer) →

Disk full

No space left on device

Cause: Logs, old kernels, container data, or a deleted file a process still holds open. Inodes can run out even when bytes look free.

df -h && df -i
sudo du -xh / --max-depth=2 2>/dev/null | sort -rh | head -20
sudo lsof +L1  # deleted but still open files

Fix: Clean the largest directory (journalctl --vacuum-size=500M for logs), restart processes holding deleted files, and add log rotation.

Full diagnosis & fix: Disk full →

High load average

load average: 24.10, 22.80, 19.50 on an 8-core box

Cause: Load counts runnable and uninterruptible (D state) tasks, so slow disks or NFS raise it as much as CPU.

uptime && nproc
vmstat 1 5  # r = CPU queue, b and wa = I/O
ps -eo state,pid,cmd | grep '^D'

Fix: Compare load to core count. High r means CPU-bound; high wa or D-state processes mean I/O. Fix the cause the numbers point to.

Full diagnosis & fix: High load average →

High CPU usage

a process sits at 100%+ CPU in top

Cause: A busy loop, a runaway query, GC thrash, or simply more traffic than the box can serve.

top -o %CPU
pidstat -u 1 5
sudo perf top -p <pid>

Fix: Find the process, then the thread and function (perf, py-spy, jstack). Check whether it's user time (app code) or system time (kernel, syscalls).

Full diagnosis & fix: High CPU usage →

Permission denied

bash: ./script.sh: Permission denied / open(...) failed (13: Permission denied)

Cause: Missing execute or read bit, wrong owner, a noexec mount, or SELinux/AppArmor denying access despite correct modes.

ls -l <file> && namei -l <path>
mount | grep noexec
sudo ausearch -m avc -ts recent  # SELinux denials

Fix: chmod +x for scripts, fix ownership with chown, and check every parent directory has the execute bit (namei shows it). Don't chmod 777.

Full diagnosis & fix: Permission denied →

Address already in use

bind: address already in use / EADDRINUSE :::3000

Cause: Another process (often an old copy of your own app) is already listening on the port.

sudo ss -ltnp 'sport = :3000'
sudo lsof -i :3000
kill <pid>  # SIGTERM first, -9 only if it ignores it

Fix: Stop the old process or change the port. For quick restarts that hit TIME_WAIT, set SO_REUSEADDR in the server.

Full diagnosis & fix: Address already in use →

Too many open files

EMFILE: too many open files / accept4: too many open files

Cause: The process hit its file descriptor limit (often 1024): too many connections, or a descriptor leak.

ulimit -n
cat /proc/<pid>/limits | grep 'open files'
ls /proc/<pid>/fd | wc -l

Fix: Raise the limit where the process starts (LimitNOFILE in the systemd unit, not just ulimit in a shell) and check that the count doesn't keep growing.

Full diagnosis & fix: Too many open files →

DNS resolution failures

Temporary failure in name resolution / Could not resolve host

Cause: Wrong or unreachable resolver in /etc/resolv.conf, systemd-resolved trouble, or a firewall blocking port 53.

cat /etc/resolv.conf
resolvectl status
dig example.com @1.1.1.1 +short

Fix: If dig against a public resolver works but the default fails, fix the local resolver config. If both fail, it's network or firewall.

Full diagnosis & fix: DNS resolution failures →

systemd service fails to start

Job for <svc>.service failed because the control process exited with error code / Start request repeated too quickly (start-limit-hit)

Cause: ExecStart fails: wrong path, a missing EnvironmentFile, a User= without permission on its files, or a forking process with the wrong Type=. After 5 failed starts in 10 seconds systemd stops trying (start-limit-hit).

systemctl status <svc> --no-pager -l
journalctl -u <svc> -b -n 100 --no-pager
systemd-analyze verify /etc/systemd/system/<svc>.service
systemctl daemon-reload && systemctl reset-failed <svc>

Fix: Run the exact ExecStart line as the service's User to reproduce. After editing the unit, run daemon-reload, then reset-failed to clear the start limit.

Full diagnosis & fix: systemd service fails to start →

Disk full, but du doesn't add up (or out of inodes)

No space left on device while df -h shows free space / df says 100% but du finds far less

Cause: Two different cases. df -i at 100% means you ran out of inodes (millions of small files: sessions, cache, mail queues). df larger than du means deleted files are still held open by a running process, and the space isn't freed until it closes them.

df -i
sudo lsof +L1
sudo find /var -xdev -type f | cut -d/ -f3 | sort | uniq -c | sort -n | tail
sudo truncate -s 0 /proc/<pid>/fd/<fd>   # free space held by a deleted-but-open file

Fix: Restart or signal the process holding deleted logs, and fix logrotate (copytruncate or a postrotate reload). For inodes, delete the small-file pile and add a cleanup job.

Full diagnosis & fix: Disk full, but du doesn't add up (or out of inodes) →

Container exit codes quick reference

CodeMeaningUsual cause
0Clean exitThe main process finished. In a long-running container, it means nothing kept PID 1 running.
1Application errorUncaught exception, bad config, missing env var. Read the logs.
2Misuse of a shell builtin / bad argumentsShell syntax error or an invalid flag. Common when an entrypoint script runs under sh but uses bash syntax.
126Command not executablePermission problem or not a binary. Check chmod +x and the shebang.
127Command not foundTypo in command/entrypoint, or the binary isn't in the image or PATH.
130SIGINT (128 + 2)Interrupted with Ctrl-C, or a tool that forwards SIGINT on shutdown.
137SIGKILL (128 + 9)OOM killer, or a stop/terminationGracePeriod timeout ended in a kill.
139SIGSEGV (128 + 11)Segmentation fault: native library crash or a binary built for the wrong libc.
143SIGTERM (128 + 15)Graceful stop requested (scale down, rollout, docker stop). Normal unless unexpected.

Any code above 128 is a signal: subtract 128 to get the signal number. 137 = 128 + 9 (SIGKILL), 143 = 128 + 15 (SIGTERM), 139 = 128 + 11 (SIGSEGV). More detail in Kubernetes exit codes explained.

HTTP status codes for ops

CodeMeaningWhat to check
401UnauthorizedNo credentials or invalid ones: missing or expired token, wrong auth header. Fix the credential, not permissions.
403ForbiddenAuthenticated but not allowed: IAM/RBAC, WAF rule, IP allowlist, S3 bucket policy. S3 also returns 403 for a missing key when you lack ListBucket.
404Not foundWrong path, a missing Ingress rule or host header, or a proxy rewrite that strips a prefix. Check which hop answered.
429Too many requestsRate limited by an API, registry or your own gateway. Back off with the Retry-After header, then cache or batch.
499Client closed request (Nginx)The client gave up before the upstream answered. Usually a slow backend combined with a client or load balancer timeout.
500Internal server errorThe application threw. The stack trace is in the app logs, not the proxy logs.
502Bad gatewayThe proxy got no valid response: upstream down, wrong port, crashed mid-request, or keep-alive mismatch.
503Service unavailableNo healthy upstream: zero ready endpoints, all targets failing health checks, maintenance mode, or overload shedding.
504Gateway timeoutThe upstream accepted but answered too slowly for the proxy timeout (60 s default in Nginx and AWS ALB).

The fastest split: 4xx means the request or the caller is the problem, 5xx means a server or a hop between you and it. For 502 and 504, read the proxy's error log before the app's. More in the Nginx reverse proxy guide.

Frequently asked questions

How do I fix CrashLoopBackOff in Kubernetes?

Run kubectl describe pod <pod> to read the Last State exit code, then kubectl logs <pod> --previous to see the output of the container that crashed. Exit code 1 points to an application or config error, 137 to an out-of-memory kill or failed liveness probe, and 127 to a wrong command. Fix that underlying cause; restarting the pod or deleting it will not.

What does exit code 137 mean?

Exit code 137 means the process received SIGKILL (128 + 9). In Kubernetes and Docker it is usually the OOM killer ending a container that exceeded its memory limit; kubectl describe shows Reason: OOMKilled and docker inspect shows OOMKilled: true. If OOMKilled is false, the container was killed after ignoring SIGTERM during a stop.

How do I fix ImagePullBackOff?

Read the pod events with kubectl describe pod. "not found" or "manifest unknown" means the image name or tag is wrong; "unauthorized" means the pod needs an imagePullSecret for the private registry in the same namespace; "no such host" or a timeout means the node can't reach the registry.

How do I fix Docker permission denied on /var/run/docker.sock?

Add your user to the docker group with sudo usermod -aG docker $USER, then log out and back in (or run newgrp docker) so the shell picks up the new group. Avoid chmod 666 on the socket, because anyone on the machine could then control Docker, which is equivalent to root.

How do I release a stuck Terraform state lock?

First make sure no other terraform plan or apply is running, in CI or on a teammate's machine. Then run terraform force-unlock <LOCK_ID>, using the ID printed in the Error acquiring the state lock message. Unlocking a lock that is actually in use can corrupt state.

How do I fix git push rejected (non-fast-forward)?

The remote branch has commits you don't have. Run git pull --rebase origin <branch> to replay your commits on top of the remote, resolve any conflicts, then git push. Only use git push --force-with-lease if you intend to overwrite the remote, and never plain --force on a shared branch.

What is the difference between a 502 and a 504 error?

A 502 Bad Gateway means the proxy or load balancer got no valid response from the upstream: nothing was listening, the connection was refused or reset, or the app crashed mid-request. A 504 Gateway Timeout means the upstream accepted the connection but did not answer before the proxy timeout, which is 60 seconds by default in Nginx and on AWS Application Load Balancers. For a 502, check that the app is up and on the right port; for a 504, find the slow request.

How do I fix x509: certificate has expired or is not yet valid?

Check the dates the server actually presents with echo | openssl s_client -connect host:443 -servername host | openssl x509 -noout -dates. If notAfter is in the past, renew the certificate, reload the server so it picks up the new file, and confirm the intermediate certificate is current too. If the dates look valid, the client's clock is wrong. In Kubernetes, check cert-manager Certificates with kubectl get certificate -A and control-plane certificates with kubeadm certs check-expiration.

How do I fix AWS AccessDenied is not authorized to perform?

Run aws sts get-caller-identity to confirm which role or user is making the call, since the wrong profile is the most common cause. Then read the end of the error: "because no identity-based policy allows" means the role needs that permission, while "with an explicit deny in a service control policy" or "permissions boundary" means a policy outside the role blocks it. aws iam simulate-principal-policy tests a fix before you apply it.

How do I fix Postgres FATAL: sorry, too many clients already?

The total number of connections from all app instances has reached max_connections, which defaults to 100. Count them with SELECT state, count(*) FROM pg_stat_activity GROUP BY state. Put a pooler such as PgBouncer in transaction mode between the apps and the database, size each app's pool so the total fits, and set idle_in_transaction_session_timeout so abandoned transactions release their slots.

How do I fix Helm another operation (install/upgrade/rollback) is in progress?

A previous Helm run was interrupted and left the release in a pending state. Make sure no other Helm job is running, read helm history <release> to find the last revision marked deployed, and run helm rollback <release> <revision>. Prevent it with a CI concurrency group and a Helm --timeout shorter than the CI job timeout, so Helm can record the failure before the runner is killed.