Kubernetes multi-container pod: how to get network traffic between pods ... 502 error?

12/27/2020

I am working on fixing some errors in an existing Kubernetes multi-container one pod deployment. I have part of it fixed; I just am missing the syntax to route the traffic from the 'frontend' container to the 'backend' one.

The YAML file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: minikube-hello-world
  labels:
    app: hello-world
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hello-world
  template:
    metadata:
      labels:
        app: hello-world
    spec:
      containers:
        - name: hello-world-frontend
          image: frontend:latest
          imagePullPolicy: Never
          ports:
            - containerPort: 80
        - name: hello-world-backend
          image: backend:latest
          imagePullPolicy: Never
          ports:
            - containerPort: 80
---
kind: Service
apiVersion: v1
metadata:
  name: hello-world-service
spec:
  selector:
    app: hello-world
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 31443
  type: LoadBalancer

When I run minikube service hello-world-service I get the web page itself, but the backend service doesn't connect correctly, Nginx instead showing a 502 Bad Gateway error.

I've drilled down into the Kubenetes documentation and I've tried hostPort various places but I still don't have it right.

Any help would be much appreciated!

-- Mark McWiggins
kubernetes
minikube
nginx

1 Answer

12/27/2020

As Christian Altamirano Ayala comments above,

Both containers can't be on the same port. (I should have thought of this.)

I changed the frontend to port 8080:

    spec:
      containers:
        - name: hello-world-frontend
          image: frontend:latest
          imagePullPolicy: Never
          ports:
            - containerPort: 8080
        - name: hello-world-backend
          image: backend:latest
          imagePullPolicy: Never
          ports:
            - containerPort: 80

And the mapping of the NodePort to 8080 also:

kind: Service
apiVersion: v1
metadata:
  name: hello-world-service
spec:
  selector:
    app: hello-world
  ports:
  - protocol: TCP
    nodePort: 31443
    port: 8080
  type: LoadBalancer

And this works. Thanks!

-- Mark McWiggins
Source: StackOverflow