如何从容器内运行的脚本访问Docker容器的元数据? [英] How to access the metadata of a docker container from a script running inside the container?
问题描述
我试图了解是否可以使用bash脚本读取容器的元数据(尤其是标签)属性。
I am trying to understand whether it is possible to read the metadata (Labels, in particular) properties of a container using a bash script.
例如,如果有一个类似Dockerfile的文件:
For instance, if there is a Dockerfile like:
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
有什么方法可以访问bash shell中的 abc标签的值?如果是这样,怎么办?
Is there any way to access the value of the "abc" label inside the bash shell? If so, how?
推荐答案
要获取标签(以及远程API中的所有内容),可以将套接字传递到容器并在容器内使用curl> = 7.40(这是支持-unix-socket
标志的最低版本),以通过套接字访问远程API:
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:
Dockerfile:
FROM ubuntu:16.04
RUN apt-get update \
&& apt-get install curl -y
LABEL abc = abc_value1
构建并运行
docker build -t image1 .
docker run -v /var/run/docker.sock:/var/run/docker.sock -it image1 /bin/bash
从容器内部
curl --unix-socket /var/run/docker.sock http:/containers/$(hostname)/json
从这里,您将拥有大量的JSON(类似于docker inspect)。然后,您可以使用CLI工具,例如 jq
拔出标签。
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.
在Docker网站上查看更多信息: https://docs.docker.com/engine/reference / api / docker_remote_api /#/ docker-remote-api
See more information on docker's website: https://docs.docker.com/engine/reference/api/docker_remote_api/#/docker-remote-api
所有这些-这不是很安全,环境变量是可能是更好的选择。
这篇关于如何从容器内运行的脚本访问Docker容器的元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!