Show Kubernetes pod name from docker container running a .Net Core API

3/5/2021

Having a .NET Core API running inside a docker container on a Kubernetes cluster: how to tell the API the name of the pod.

Is there anyway to forward or inject the information?

This could be usefull to pin issues down to pods by enriching logs or connections.

-- monty
.net
.net-core
docker
kubernetes

1 Answer

3/5/2021

The Downward API provides the way to expose information to containers.

Description from the docs:

This page shows how a Pod can use environment variables to expose information about itself to Containers running in the Pod. Environment variables can expose Pod fields and Container fields.

Refer this example to see how information is exposed as the environment variables on the containers.

apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars-fieldref
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c"]
      args:
      - while true; do
          echo -en '\n';
          printenv MY_NODE_NAME MY_POD_NAME MY_POD_NAMESPACE;
          printenv MY_POD_IP MY_POD_SERVICE_ACCOUNT;
          sleep 10;
        done;
      env:
        - name: MY_NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MY_POD_SERVICE_ACCOUNT
          valueFrom:
            fieldRef:
              fieldPath: spec.serviceAccountName
  restartPolicy: Never

The script running inside the container can then access this information from the environment variable.

-- Krishna Chaurasia
Source: StackOverflow