TL;dr

k8s有Downward API可以将Pod和Container字段呈现给运行中的容器。那么docker呢?

答案是:使用docker API

使用 -v /var/run/docker.sock:/var/run/docker.sock 映入容器,或者,enabled the docker remote API (via -H tcp://0.0.0.0:4243 for instance)

docker run -it --rm --name tmpnginx -p80 -v /var/run/docker.sock:/var/run/docker.sock nginx:1.16.1 bash
docker exec -it tmpnginx bash
# 获取容器id
containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
# echo $containerID
# 获取容器名字
containerName=`curl -s --unix-socket /var/run/docker.sock http:/v1.40/containers/${containerID}/json | jq -r '.Name'`
imageName=`curl -s --unix-socket /var/run/docker.sock http:/v1.40/containers/${containerID}/json | jq -r '.Config.Image'`
# | jq -r '.NetworkSettings.Ports["80/tcp"][0].HostPort'
# | jq -r '.Config.Image'
# | jq -r '.Name'
# | jq -r '.Id'

ref