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
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).
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