Connecting angular front end to API using kubernetes service

11/27/2019

in my env file for my angular frontend I have the API endpoint set as localhost:8000 because my API listens on that port, but it is in a separate pod is this correct or am I meant to use the name I gave to the backend service in the deployment file. Second, how do I connect the backend service is how I have it done in the deployment file below correct?

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ai-api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ai-api
  template:
    metadata:
      labels:
        app: ai-api
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": linux
      containers:
      - name: ai-api
        image: test.azurecr.io/api:v5
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 250m
            memory: 256Mi
        ports:
        - containerPort: 8000
          name: ai-api
---
apiVersion: v1
kind: Service
metadata:
  name: ai-api
spec:
  ports:
  - port: 8000
  selector:
    app: ai-api
---
# Frontend
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ai-front
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ai-front
  template:
    metadata:
      labels:
        app: ai-front
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": linux
      containers:
      - name: ai-front
        image: test.azurecr.io/front-end:v5.1
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 250m
            memory: 256Mi
        ports:
        - containerPort: 80
        env:
        - name: api
          value: "ai-api"
---
apiVersion: v1
kind: Service
metadata:
  name: ai-front
spec:
  type: LoadBalancer
  ports:
  - port: 80
  #Tells loadbalancer which deployment to use
  selector:
    app: ai-front
-- Conor Donohoe
kubernetes

1 Answer

11/29/2019

You mentioned that you have API endpoint set as localhost:8000 for your frontend which is not correct as localhost is referring to the same pod from which the request is send from (so it means "connect to myself"). Change it to ai-api:8000. And also make sure that your api server is listening on 0.0.0.0:8000 and not on localhost:8000.

I also see that you are passing the name of your backend service to the frontend pod:

env:
- name: api
  value: "ai-api"

and if you are using this env to connect to your backend app it would stand in contradiction with your earlier statement that you are connecting to localhost:8000.

-- HelloWorld
Source: StackOverflow