简体   繁体   English

如何从容器内运行的脚本访问docker容器的元数据?

[英]How to access the metadata of a docker container from a script running inside the container?

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? 有没有办法在bash shell中访问“abc”标签的值? If so, how? 如果是这样,怎么样?

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). 从这里你将拥有一大块JSON(类似于docker inspect)。 You can then use a CLI tool like jq to pluck out the labels. 然后,您可以使用jq类的CLI工具来拔出标签。

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. 所有这一切 - 这不是很安全,环境变量可能是一个更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM