How to get Docker Compose/Docker Swarm/Kubernetes Container Number

3/31/2021

All container orchestrators like Docker Compose/Docker Swarm/Kubernetes provide a way to set the number of containers to run. While running inside one of these containers, is it possible to determine the number of the container e.g. 5 of 10 where the number I'm looking for is 5. Is this exposed as an environment variable or is there another way to get this number?

-- Muhammad Rehan Saeed
docker
docker-compose
docker-swarm
kubernetes

1 Answer

4/1/2021

In kubernetes you can get container names using jsonpath

containernames=$(kubectl  -n kube-system get pod <replacepodname> -o jsonpath={.spec.containers[*].name})

Then you can read the names one by one

echo $containernames | awk '{print $1 }' echo $containernames | awk '{print $2 }'

or

set -- $containernames echo $1 echo $2

-- subudear
Source: StackOverflow