The pod index is exposed as via pod label app.kubernetes.io/pod-index
as explained in Ordinal Index and Pod index label
You have two options to read this pod label from within the container:
The Expose Pod Information to Containers Through Environment Variables
has been explained in other answers but here it is again (look for MY_POD_INDEX
and pod-index
):
...
spec:
template:
...
spec:
containers:
- name: test-container
image: registry.k8s.io/busybox
command: [ "sh", "-c"]
args:
- while true; do
echo -en '\n';
printenv MY_POD_INDEX;
sleep 10;
done;
env:
- name: MY_POD_INDEX
valueFrom:
fieldRef:
fieldPath: metadata.labels['apps.kubernetes.io/pod-index']
restartPolicy: Never
and via files it would be like this:
...
spec:
...
template:
...
spec:
containers:
- name: client-container
image: registry.k8s.io/busybox
command: ["sh", "-c"]
args:
- while true; do
if [[ -e /etc/podinfo/labels ]]; then
echo -en '\n\n'; cat /etc/podinfo/labels; fi;
sleep 5;
done;
volumeMounts:
- name: podinfo
mountPath: /etc/podinfo
volumes:
- name: podinfo
downwardAPI:
items:
- path: "labels"
fieldRef:
fieldPath: metadata.labels
in this case the /etc/podinfo/labels
from the downwardAPI volume will contain something like:
app.kubernetes.io/pod-index="1"