bash 如何从容器内运行的脚本访问 docker 容器的元数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37439887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the metadata of a docker container from a script running inside the container?
提问by egordoe
I am trying to understand whether it is possible to read the metadata (Labels, in particular) properties of a container using a bash script.
我试图了解是否可以使用 bash 脚本读取容器的元数据(特别是标签)属性。
For instance, if there is a Dockerfile like:
例如,如果有一个 Dockerfile,如:
FROM busybox
LABEL abc = abc_value1
And, if I build and run an image based on the file above, like so:
而且,如果我根据上面的文件构建并运行一个图像,如下所示:
docker build . -t image1
docker run -ti image1 /bin/bash
Is there any way to access the value of the "abc" label inside the bash shell? If so, how?
有没有办法访问bash shell中“abc”标签的值?如果是这样,如何?
回答by Josh
To get the labels (and anything from the remote API), you could pass the socket into the container and use curl >= 7.40 (it's the minimum version that supports --unix-socket
flag) from within the container to access the remote API via the socket:
要获取标签(以及来自远程 API 的任何内容),您可以将套接字传递到容器中并使用 curl >= 7.40(它是支持--unix-socket
标志的最低版本)从容器内通过套接字访问远程 API:
Dockerfile:
Dockerfile:
FROM ubuntu:16.04
RUN apt-get update \
&& apt-get install curl -y
LABEL abc = abc_value1
Build and run
构建并运行
docker build -t image1 .
docker run -v /var/run/docker.sock:/var/run/docker.sock -it image1 /bin/bash
From inside the container
从容器内部
curl --unix-socket /var/run/docker.sock http:/containers/$(hostname)/json
From here you'll have a huge chunk of JSON (similar to docker inspect). You can then use a CLI tool like jq
to pluck out the labels.
从这里您将拥有大量 JSON(类似于 docker inspect)。然后,您可以使用 CLI 工具jq
来提取标签。
See more information on docker's website: https://docs.docker.com/engine/reference/api/docker_remote_api/#/docker-remote-api
在 docker 的网站上查看更多信息:https: //docs.docker.com/engine/reference/api/docker_remote_api/#/docker-remote-api
All that said-- this isn't very secure, and environment variables are probably a better bet.
综上所述 - 这不是很安全,环境变量可能是更好的选择。