How to replace hard-coded IP in deployment with service endpoint in kubernetes

1/22/2021

After creating a service and an endpoint object ->

---
apiVersion: v1
kind: Service
metadata:
  name: external-service
  namespace: default
spec:
  ports:
  - protocol: TCP
    port: 8200
---
apiVersion: v1
kind: Endpoints
metadata:
  name: external-service
subsets:
  - addresses:
      - ip: $EXTERNAL_ADDR
    ports:
      - port: 8200

How can I point to the service in the deployment.yaml file. I want to remove the hardcoded IP the env variable

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: devwebapp
  labels:
    app: devwebapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: devwebapp
  template:
    metadata:
      labels:
        app: devwebapp
    spec:
      serviceAccountName: internal-app
      containers:
      - name: app
        image: app:k8s
        imagePullPolicy: Always
        env:
        - name: ADDRESS
          value: "http://$EXTERNAL_SERVICE:8200"

Simply changing the value to http://external-service didn't help.

Thank you in advance!

-- anushjay
kubernetes

2 Answers

1/22/2021

I had to set the value to http://external-service:8200. The port was specified in the Endpoints so didn't bother to add it in the deployment.

-- anushjay
Source: StackOverflow

1/22/2021

you don't need to create endpoints separately just use selector in service spec. it will automatically create desired endpoints.

this one will work for you:

---
apiVersion: v1
kind: Service
metadata:
  name: external-service
  namespace: default
spec:
  selector:
    app: devwebapp
  ports:
  - protocol: TCP
    port: 8200
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: devwebapp
  labels:
    app: devwebapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: devwebapp
  template:
    metadata:
      labels:
        app: devwebapp
    spec:
      serviceAccountName: internal-app
      containers:
      - name: app
        image: app:k8s
        imagePullPolicy: Always
        ports:
        - containerPort: 8200
        env:
        - name: ADDRESS
          value: http://external-service:8200
-- Emon46
Source: StackOverflow