How to Fix Docker 502 Bad Gateway on Kubernetes Pod
The Root Cause
On Kubernetes Pods, a “Docker 502 Bad Gateway” typically indicates that the application running within the container itself is either not listening on the expected port, has crashed, or is taking too long to respond to requests. This prevents the Kubernetes service or Ingress controller from establishing a successful connection to the Pod’s endpoint, resulting in the upstream error.
Quick Fix (CLI)
# 1. Identify the problematic Deployment (replace <deployment-name> with your actual deployment name)
kubectl get deployments
# 2. Trigger a rollout restart for the deployment's pods. This forces new pods to be scheduled.
kubectl rollout restart deployment/<deployment-name>
# 3. Optionally, watch the rollout status to ensure new pods are created successfully
kubectl rollout status deployment/<deployment-name>
Configuration Check
File to edit: Kubernetes Deployment YAML (deployment.yaml) and Service YAML (service.yaml).
What lines to change: Ensure the containerPort defined in your Pod’s container specification (within deployment.yaml) matches the port your application actually binds to internally. Then, verify that the targetPort in your Kubernetes Service definition (service.yaml) correctly points to this containerPort. If using an Ingress, also verify the service.port.number in your Ingress manifest matches the port in your Service manifest.
# Example: deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-web-app
spec:
template:
spec:
containers:
- name: my-app-container
image: my-company/my-web-app:1.0.0
ports:
- containerPort: 8080 # <--- ENSURE this is the port your application truly listens on (e.g., in Node.js app.listen(8080))
---
# Example: service.yaml
apiVersion: v1
kind: Service
metadata:
name: my-web-app-service
spec:
selector:
app: my-web-app # Must match labels in deployment.yaml
ports:
- protocol: TCP
port: 80 # The port the Service itself exposes
targetPort: 8080 # <--- THIS MUST MATCH the containerPort from deployment.yaml
Verification
# 1. Check the status of your pods after making changes and reapplying manifests
# Ensure pods are in 'Running' state and not 'CrashLoopBackOff'
kubectl get pods -l app=my-web-app # Replace 'app=my-web-app' with your pod's actual selector label
# 2. Inspect the logs of the newly created or restarted pod for application startup messages and no errors
kubectl logs <new-pod-name> # Get the new pod name from 'kubectl get pods'
# 3. Access the application via its Service or Ingress endpoint to confirm the 502 is resolved
# If using Ingress (recommended for external access):
curl -I http://your-app.webtoolswiz.com/ # Replace with your Ingress host
# If using a NodePort or LoadBalancer Service:
# First, get the Service's external IP and port
kubectl get svc my-web-app-service
# Then, curl the endpoint
curl -I http://<service-external-ip>:<service-port>/