Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Kubernetes POD's full Id from inside of itself ( running container )

How to Get a container’s full id from inside of itself in Kubernetes. I want to add container id in my application log which is running as Kubernetes container

like image 945
Kundan Kumar Avatar asked Nov 11 '19 11:11

Kundan Kumar


People also ask

How do I get environment variables in Kubernetes?

There are two ways to define environment variables with Kubernetes: by setting them directly in a configuration file, from an external configuration file, using variables, or a secrets file. This tutorial shows both options, and uses the Humanitec getting started application used in previous tutorials.


2 Answers

There are two ways to expose Pod and Container fields to a running Container:

  • Environment variables
  • Volume Files

Together, these two ways of exposing Pod and Container fields are called the Downward API.

So, simply using environment variables you can inject any metadata of a pod into the running container.


Post Comment Update - As per the kubernetes documentation each name has a UID that is appended to the name of the resource, for example, a pod or container which will provide with for a way to get a unique ID to be used for logging.

metadata.name = myimage + unique id

note* -the only caveat here is the fact that UID changes on each upgrade so It would be better to assign a unique ID from your side to identify the container or pod in combination with K8 UID.

Here's an example of YAML.

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_POD_ID   // <--- here you inject env into container
          valueFrom:
            fieldRef:
              fieldPath: metadata.name   // <--- set value of the env var to pod name
        - name: MY_POD_SERVICE_ACCOUNT
          valueFrom:
            fieldRef:
              fieldPath: spec.serviceAccountName
  restartPolicy: Never

reference link.

like image 94
damitj07 Avatar answered Nov 16 '22 02:11

damitj07


The HOSTNAME environment variable is readily available in any container running on Kubernetes and gives the unique name of the pod in which the container is running. Use the means provided by the logging framework to acccesss the environment variable and make it part of the logging pattern, or to programatically add its value to log entries.

That should do for application logging purposes assuming there is only one application container in the pod (which is regarded as a best practice anyway).

like image 30
apisim Avatar answered Nov 16 '22 02:11

apisim