Get service IP:PORT as environment variable in pod

Viewed 32

I have a service running and attached to a pod. In the pod, I need to define env variable which has to point to itself. If I run locally, I would set path to localhost:8080 and it works. How can I set env variable to point to the service itself?

user@user % kubectl get svc
NAME                 TYPE           CLUSTER-IP     EXTERNAL-IP       PORT(S)             AGE
my-service           LoadBalancer   10.96.116.26   129.153.28.245    8080:31495/TCP      21h
kubernetes           ClusterIP      10.96.0.1      <none>            443/TCP,12250/TCP   5d18h

If the configuration is:

spec:
      containers:
      - name: myapp   
        image: path/to/imageregistry/image:v1.0.0-amd64
        env:
          - name: BASE_PATH
            value: "129.153.28.245:8080"

App is working, in a sense that If I open in browser 129.153.28.245:8080/app/pages it will open the website. If I replace <EXTERTNAL-IP> with <CLUSTER-IP> it's not loading.

How to retrieve <EXTERTNAL-IP> from the service and put into env variable, something like:

env:
    - name: BASE_PATH
      value: "<EXTERNAL-IP-FROM-SERVICE-NAME>:8080"

or is there another and better approach to do that?

Here's the full Deployment and Service yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  selector:
    matchLabels:
      app: myapp
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp    
        image: xxx.ocir.io/xxxxxx/myrepo/myimage:v1.0.0-amd64
        env:
          - name: BASE_PATH
            value: "129.153.28.245:8080"
        ports:
        - containerPort: 80
      imagePullSecrets:
      - name: ocirsecret
---
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: LoadBalancer
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    app: myapp
0 Answers
Related