how to get container name from inside? docker.io

只愿长相守 提交于 2019-12-12 14:08:23

问题


How can I get docker's container name from inside the container?

I can't use inspect because I have to use an script from inside the container to get info from a JSON url.


回答1:


If you mean the Container ID its available in the env as the hostname variable. It should be interchangeable with the name for most operations.

env
HOSTNAME=5252eb24b296
TERM=xterm
....

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5252eb24b296        ubuntu:14.04        "bash"              23 seconds ago      Up 22 seconds                           test



回答2:


I think, most reliable way to use combination of --cidfile and -v options.

docker run --cidfile=/tmp/container.id -v /tmp/container.id:/tmp/container.id ${IMAGE}

If you will start container this way, you can read /tmp/container.id from inside of your container.




回答3:


if you have docker inside container,
(you need to bind -v /var/run/docker.sock:/var/run/docker.sock)
and the hostname was not modified you can get it via:
docker inspect -f '{{.Name}}' $HOSTNAME

but this solution can be used only in edge cases.




回答4:


In the case of docker-compose we had a / in front of the hostname so using cut we removed that.

docker inspect -f '{{ .Name }}' "$HOSTNAME" | cut -c 2-


来源:https://stackoverflow.com/questions/26979038/how-to-get-container-name-from-inside-docker-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!