Interview Prep/Kubernetes/Services, DNS, Ingress and NetworkPolicy

ingress-nginx returns `502 Bad Gateway`, and its log shows `upstream prematurely closed connection while reading response header from upstream` or `connect() failed (111: Connection refused) while connecting to upstream`.

IntermediateTroubleshootingServices, DNS, Ingress and NetworkPolicy
Answer

Likely causes → nginx reaches the Pod but the backend fails: wrong target port, app listening only on localhost, app expects TLS but nginx speaks HTTP, Pods restarting, or the app closes idle keep-alive connections earlier than nginx reuses them.

Diagnose →

kubectl logs -n ingress-nginx deploy/ingress-nginx-controller --tail=200 | grep -E '502|upstream'
kubectl get endpointslices -l kubernetes.io/service-name=shop -n shop
kubectl exec -n ingress-nginx deploy/ingress-nginx-controller -- curl -sv http://<pod-ip>:8080/

Fix → Fix the port or bind address. If the backend speaks HTTPS, add nginx.ingress.kubernetes.io/backend-protocol: "HTTPS". For keep-alive races, make the app's idle timeout longer than nginx's upstream-keepalive-timeout (60s default).

Prevent → Ready checks that reflect real serving ability and graceful shutdown (preStop sleep) so Pods leave endpoints before they stop listening.

All Kubernetes questions Roadmap: Kubernetes networking, storage & scaling

More on Services, DNS, Ingress and NetworkPolicy