Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

bash - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...