如何从容器内运行的脚本访问 docker 容器的元数据? [英] How to access the metadata of a docker container from a script running inside the container?

查看:21
本文介绍了如何从容器内运行的脚本访问 docker 容器的元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解是否可以使用 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).然后,您可以使用像 jq 这样的 CLI 工具来提取标签.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆