简体   繁体   中英

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.

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

Is there any way to access the value of the "abc" label inside the bash shell? 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:

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.

See more information on docker's website: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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